如何在Vue.js中引用' '中的文本

epggiuax  于 2023-08-07  发布在  Vue.js
关注(0)|答案(6)|浏览(140)

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

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

字符串

uqxowvwt

uqxowvwt1#

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

默认插槽中的内容,也就是您所描述的内容,在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)
  }
})


它将返回槽中连接在一起的所有文本。假设上面的例子有图标,它会返回“OK”。

p5cysglq

p5cysglq2#

对于Vue 3。

@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)

字符串

8oomwypt

8oomwypt3#

运行以下代码片段,获取parent传递的slot文本:

我用的是“ref”

<span ref="mySlot">

this.$refs.mySlot.innerHTML

字符串
注意:<slot ref="refName"></slot>不工作,因为<slot>不会呈现在html上。您必须使用<div></div><span></span> Package <slot></slot>

代码:

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'
});
<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>

的数据

zvokhttg

zvokhttg4#

您可以通过连接槽内所有子级的innerText来访问槽文本。

getSlotText() {
  return this.$slots.default.map(vnode => (vnode.text || vnode.elm.innerText)).join('');
},

字符串

ewm0tg9j

ewm0tg9j5#

我的用例非常简单,我有一个只有文本的默认插槽。以下是我如何在vue3中使用脚本设置访问文本:

<script setup lang="ts">
import { computed, useSlots } from "vue";

const slots = useSlots();

const slotText = computed(() => {
    return slots.default()[0].children; // This is the interesting line
});
</script>

字符串

vs91vp4v

vs91vp4v6#

这个[Vue Typescript] composable返回slot的reactive文本

import { useSlots, ref, type VNode, computed, watch } from 'vue';

/**
 * Get reactive reference to the current textContent of slot.
  @param {string} name the name of the slot
  @param {object} slotProps the slot bindings(props) as an object
  @returns {string} the textContent of the slot
 */
const useSlotText = <T>(name: string, slotProps: T) => {
  const slot = useSlots()[name]
  const text = ref('')

  //get text from every element in the slot recursively
  function getText(nodes?: VNode[]) {
    let text = ""
    nodes?.forEach(node => {
      if (typeof node.children === 'string') {
        text += node.children
        return
      } else if (Array.isArray(node.children) && node.children.length) {
        return getText(node.children as VNode[])
      }
    })
    return text
  }

  if (slot) {
    const nodes = slot(slotProps)
    text.value = getText(nodes)
  }

  //watch for changes and update
  watch(() => useSlots()[name], () => {
    const slot = useSlots()[name]
    if (slot)
      text.value = getText(slot(slotProps))
  })

  return computed(() => text.value)
}

字符串

相关问题