如何引用“<slot></slot>"中的文本在 Vue.js 中

2022-01-25 00:00:00 vue.js vue-component vuejs2

如何引用 Vue.js 中的文本?

Vue.component('component', {模板:`<button><slot></slot></button>`,创建:函数(){//我想在这里访问插槽中的文本}});

解决方案

注意:此答案仅适用于 Vue v2.

默认插槽内的内容,也就是您所描述的,在 Vue.js 中以 this.$slots.default 的形式公开.因此,在按钮中获取文本最简单的方法是使用 this.$slots.default[0].text.

Vue.component('component', {模板:`<button><slot></slot></button>`,创建:函数(){const buttonText = this.$slots.default[0].text;}});

问题是slot里面可能有不止一个节点,节点不一定是文本.考虑一下这个按钮:

<button><i class="fa fa-check></i>确定

在这种情况下,使用第一个解决方案将导致 undefined 因为槽中的第一个节点不是文本节点.

为了解决这个问题,我们可以从 Vue 文档中借用一个函数来渲染函数.

<块引用>

var getChildrenTextContent = function (children) {返回children.map(函数(节点){返回节点.children?getChildrenTextContent(node.children):节点.文本}).加入('')}

然后写

Vue.component("mybutton", {模板:<button><slot></slot></button>",创建(){const text = getChildrenTextContent(this.$slots.default);控制台日志(文本)}})

这将返回连接在一起的插槽中的所有文本.假设上面的示例带有图标,它将返回OK".

How to reference text that's in in Vue.js?

Vue.component('component', {
  template: `<button><slot></slot></button>`,
  created: function() {
    // i would like to access the text in slot here
  }
});

解决方案

Note: This answer applies to Vue v2 only.

The content inside the default slot, which is what you are describing, is exposed as this.$slots.default in the Vue. So the most naive way to get the text inside your button would be to use this.$slots.default[0].text.

Vue.component('component', {
  template: `<button><slot></slot></button>`,
  created: function() {
    const buttonText = this.$slots.default[0].text;
  }
});

The problem is that there may be more than one node inside the slot, and the nodes may not necessarily be text. Consider this button:

<button><i class="fa fa-check"></i> OK</button>

In this case, using the first solution will result in undefined because the first node in the slot is not a text node.

To fix that we can borrow a function from the Vue documentation for render functions.

var getChildrenTextContent = function (children) {
  return children.map(function (node) {
    return node.children
      ? getChildrenTextContent(node.children)
      : node.text
  }).join('')
}

And write

Vue.component("mybutton", {
  template:"<button><slot></slot></button>",
  created(){
    const text = getChildrenTextContent(this.$slots.default); 
    console.log(text)
  }
})

Which will return all the text in the slot joined together. Assuming the above example with the icon, it would return, "OK".

相关文章