如何引用 Vue.js 中的文本?
Vue.component('component', {
template: `<button><slot></slot></button>`,
created: function() {
// i would like to access the text in slot here
}
});
原文由 Tadas Majeris 发布,翻译遵循 CC BY-SA 4.0 许可协议
如何引用 Vue.js 中的文本?
Vue.component('component', {
template: `<button><slot></slot></button>`,
created: function() {
// i would like to access the text in slot here
}
});
原文由 Tadas Majeris 发布,翻译遵循 CC BY-SA 4.0 许可协议
5 回答4.8k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答4.7k 阅读✓ 已解决
4 回答4.3k 阅读✓ 已解决
4 回答1.8k 阅读✓ 已解决
2 回答2.6k 阅读✓ 已解决
2 回答2.5k 阅读✓ 已解决
注意:此答案仅适用于 Vue v2。
默认插槽内的内容,也就是您所描述的内容,在
this.$slots.default
.因此,在按钮中获取文本的最天真的方法是使用this.$slots.default[0].text
。问题是slot里面的节点可能不止一个,节点不一定是文本。考虑这个按钮:
在这种情况下,使用第一个解决方案将导致
undefined
因为槽中的第一个节点不是文本节点。为了解决这个问题,我们可以从 Vue 文档中借用一个用于渲染函数的函数。
”`
这将返回插槽中连接在一起的所有文本。假设上面的例子带有图标,它会返回“OK”。