Tad*_*ris 6 vue.js vue-component vuejs2
如何引用Vue.js中的文本?
Vue.component('component', {
template: `<button><slot></slot></button>`,
created: function() {
// i would like to access the text in slot here
}
});
Run Code Online (Sandbox Code Playgroud)
@bert 的答案在 Vue 2 上运行良好,但 Vue 3 插槽具有更复杂的结构。
default这是在 Vue 3 上获取插槽文本内容(从插槽)的一种方法。
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)
Run Code Online (Sandbox Code Playgroud)
默认插槽内的内容(即您所描述this.$slots.default的内容)与Vue中一样公开。因此,在按钮内获取文本的最幼稚的方式是使用this.$slots.default[0].text。
Vue.component('component', {
template: `<button><slot></slot></button>`,
created: function() {
const buttonText = this.$slots.default[0].text;
}
});
Run Code Online (Sandbox Code Playgroud)
问题在于插槽内可能有多个节点,并且这些节点不一定是文本。考虑以下按钮:
<button><i class="fa fa-check"></i> OK</button>
Run Code Online (Sandbox Code Playgroud)
在这种情况下,将使用第一种解决方案,undefined因为插槽中的第一个节点不是文本节点。
为了解决这个问题,我们可以从Vue文档中借用一个函数来提供渲染功能。
Run Code Online (Sandbox Code Playgroud)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)
}
})
Run Code Online (Sandbox Code Playgroud)
这将返回插槽中连接在一起的所有文本。假设上面的示例带有图标,它将返回“ OK”。
我正在使用“ ref”:
<span ref="mySlot">
this.$refs.mySlot.innerHTML
Run Code Online (Sandbox Code Playgroud)
小心:<slot ref="refName"></slot>不起作用,因为<slot>不在html上呈现。您必须<slot></slot>用<div></div>或包装<span></span>
<span ref="mySlot">
this.$refs.mySlot.innerHTML
Run Code Online (Sandbox Code Playgroud)
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'
});Run Code Online (Sandbox Code Playgroud)
您可以通过连接槽内所有子项的内部文本来访问槽文本。
getSlotText() {
return this.$slots.default.map(vnode => (vnode.text || vnode.elm.innerText)).join('');
},
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8886 次 |
| 最近记录: |