如何引用Vue.js中的文本?
Vue.component('component', {
template: `<button><slot></slot></button>`,
created: function() {
// i would like to access the text in slot here
}
});发布于 2017-03-22 23:28:23
注意:此答案仅适用于Vue v2。
默认插槽中的内容,即您所描述的内容,在Vue中公开为this.$slots.default。所以将文本放入按钮中最简单的方法就是使用this.$slots.default[0].text。
Vue.component('component', {
template: `<button><slot></slot></button>`,
created: function() {
const buttonText = this.$slots.default[0].text;
}
});问题是在插槽中可能有多个节点,并且这些节点不一定是文本。考虑一下这个按钮:
<button><i class="fa fa-check"></i> OK</button>在这种情况下,使用第一个解决方案将产生undefined,因为插槽中的第一个节点不是文本节点。
为了解决这个问题,我们可以从Vue文档中为render函数借用一个函数。
返回变量getChildrenTextContent =
(子){ return children.map(function (GetChildrenTextContent)){ return node.children?getChildrenTextContent(node.children):node.text }).join('') }
然后写下
Vue.component("mybutton", {
template:"<button><slot></slot></button>",
created(){
const text = getChildrenTextContent(this.$slots.default);
console.log(text)
}
})它将返回合并在一起的槽中的所有文本。假设上面的例子带有图标,它将返回"OK“。
发布于 2017-03-24 09:14:45
运行下面的代码片段,获取父级传递的插槽文本:
我使用的是"ref":
<span ref="mySlot">
this.$refs.mySlot.innerHTML注意:<slot ref="refName"></slot>不能工作,因为<slot>不是在html上呈现。您必须用<div></div>或<span></span>包装<slot></slot>
代码:
Vue.component('component', {
template: '<button>' +
'<span ref="mySlot">' +
'Text before<br />' +
'<slot name="slot1">' +
'Text by default' +
'</slot>' +
'<br />Text after' +
'</span>' +
'</button>',
mounted: function() {
console.log( this.$refs.mySlot.innerHTML);
}
});
new Vue({
el: '#app'
});<script src="https://vuejs.org/js/vue.min.js"></script>
<div id="app">
<component>
<span slot="slot1">I'm overriding the slot and text appear in this.$refs.mySlot.innerHTML !</span>
</component>
</div>
发布于 2018-10-11 05:55:50
您可以通过联接槽中所有子对象的innerText来访问槽文本。
getSlotText() {
return this.$slots.default.map(vnode => (vnode.text || vnode.elm.innerText)).join('');
},https://stackoverflow.com/questions/42950967
复制相似问题