我有一个只接受v-model="code"代码的组件(prism-editor)。这意味着,代码必须通过code发送到组件
Code.vue
<template>
<prism-editor class="my-editor" v-model="code"
:highlight="highlighter" :line-numbers="numbers"/>
</template>
<script>
import { PrismEditor } from 'vue-prism-editor';
export default {
components: {
PrismEditor,
},
data: () => ({
code: this.$slots,
numbers: true
}),
}
</script>我想从一个插槽中绑定一个名为Code的父组件:
Page.vue
<template>
<code language="c">
int main() {
printf('Hello World!');
}
</code>
<template>
<script>
import Code from 'code.vue'
export default {
components: {
'code': Code
}
}
</script>在我的Code组件中,我必须找到一种方法来获取插槽数据,并将其直接传递给要发送给v-model='code'的code变量。不幸的是,下面的代码不起作用,因为我不知道如何从父slot中获取数据
data: () => ({
code: this.$slots // Which obviously doesn't work...
})换句话说,我只想获得在code标记内发送的所有原始内容:
<code>all this content...</code>`这个是可能的吗?
.
├── Code.vue
└── Page.vue发布于 2020-08-15 22:36:13
一个很好的问题,为了解决这个问题,您必须在Vuejs下面的一层,并使用DOM [read more here]中的textContent属性
有了这个属性,您就可以访问DOM元素中的内容,所以在本例中应该是这样的:
/*
* Template
*/
<div ref="mySlot">
<slot></slot>
</div>
/*
* Javascript
*/
this.$refs.mySlot.textContent;我在Codesandbox中为您设置了一个很好的示例:
https://codesandbox.io/s/gallant-resonance-7unn2?file=/src/components/Code.vue
对于未来的挑战:
总是试着看看你是否能用纯Javascript解决这个问题。快乐的编码伙伴;
https://stackoverflow.com/questions/63426511
复制相似问题