如何引用Vue.js中的文字?
LOCALE_ID
答案 0 :(得分:5)
默认插槽中的内容(您正在描述的内容)在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文档中借用一个函数来渲染函数。
var getChildrenTextContent = function (children) { return children.map(function (node) { 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)
}
})
这将返回连接在一起的插槽中的所有文本。假设上面带有图标的示例,它将返回,&#34; OK&#34;。
答案 1 :(得分:4)
我正在使用"ref":
<span ref="mySlot">
this.$refs.mySlot.innerHTML
小心:<slot ref="refName"></slot>
不能正常工作,因为<slot>
不会在html上呈现。
您必须使用<slot></slot>
或<div></div>
<span></span>
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'
});
&#13;
<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>
&#13;
答案 2 :(得分:1)
您可以通过加入插槽内所有子代的innerText来访问插槽文本。
getSlotText() {
return this.$slots.default.map(vnode => (vnode.text || vnode.elm.innerText)).join('');
},
答案 3 :(得分:0)
@bert的答案在Vue 2上效果很好,但是Vue 3插槽的结构更为复杂。
这是在Vue 3上获取广告位文本内容(从default
插槽)的一种方法。
const getSlotChildrenText = children => children.map(node => {
if (!node.children || typeof node.children === 'string') return node.children || ''
else if (Array.isArray(node.children)) return getSlotChildrenText(node.children)
else if (node.children.default) return getSlotChildrenText(node.children.default())
}).join('')
const slotTexts = this.$slots.default && getSlotChildrenText(this.$slots.default()) || ''
console.log(slotTexts)