首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Vue.js中引用“<slot></slot>”中的文本

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

Stack Overflow用户
提问于 2017-03-22 19:57:07
回答 5查看 17.5K关注 0票数 10

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

代码语言:javascript
复制
Vue.component('component', {
  template: `<button><slot></slot></button>`,
  created: function() {
    // i would like to access the text in slot here
  }
});
EN

回答 5

Stack Overflow用户

发布于 2017-03-22 23:28:23

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

默认插槽中的内容,即您所描述的内容,在Vue中公开为this.$slots.default。所以将文本放入按钮中最简单的方法就是使用this.$slots.default[0].text

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

问题是在插槽中可能有多个节点,并且这些节点不一定是文本。考虑一下这个按钮:

代码语言:javascript
复制
<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('') }

然后写下

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

它将返回合并在一起的槽中的所有文本。假设上面的例子带有图标,它将返回"OK“。

票数 14
EN

Stack Overflow用户

发布于 2017-03-24 09:14:45

运行下面的代码片段,获取父级传递的插槽文本:

我使用的是"ref"

代码语言:javascript
复制
<span ref="mySlot">

this.$refs.mySlot.innerHTML

注意:<slot ref="refName"></slot>不能工作,因为<slot>不是在html上呈现。您必须用<div></div><span></span>包装<slot></slot>

代码:

代码语言:javascript
复制
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'
});
代码语言:javascript
复制
<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>

票数 6
EN

Stack Overflow用户

发布于 2018-10-11 05:55:50

您可以通过联接槽中所有子对象的innerText来访问槽文本。

代码语言:javascript
复制
getSlotText() {
  return this.$slots.default.map(vnode => (vnode.text || vnode.elm.innerText)).join('');
},
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42950967

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档