<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>
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)
}
6条答案
按热度按时间uqxowvwt1#
默认插槽中的内容,也就是您所描述的内容,在Vue中被公开为
this.$slots.default
。因此,在按钮中获取文本的最简单的方法是使用this.$slots.default[0].text
。字符串
问题是槽内可能有多个节点,并且节点不一定是文本。看看这个按钮:
型
在这种情况下,使用第一种解决方案将导致
undefined
,因为槽中的第一个节点不是文本节点。为了解决这个问题,我们可以从Vue文档中借用一个函数来实现渲染函数。
型
然后写
型
它将返回槽中连接在一起的所有文本。假设上面的例子有图标,它会返回“OK”。
p5cysglq2#
对于Vue 3。
@bert的答案在Vue 2上运行良好,但Vue 3插槽的结构更复杂。
下面是一种在Vue 3上获取插槽文本内容(从
default
插槽)的方法。字符串
8oomwypt3#
运行以下代码片段,获取parent传递的slot文本:
我用的是“ref”
字符串
注意:
<slot ref="refName"></slot>
不工作,因为<slot>
不会呈现在html上。您必须使用<div></div>
或<span></span>
Package<slot></slot>
代码:
的数据
zvokhttg4#
您可以通过连接槽内所有子级的innerText来访问槽文本。
字符串
ewm0tg9j5#
我的用例非常简单,我有一个只有文本的默认插槽。以下是我如何在vue3中使用脚本设置访问文本:
字符串
vs91vp4v6#
这个[Vue Typescript] composable返回slot的reactive文本
字符串