如何在vue中利用$slot 获取插槽的节点

如何在vue中利用$slot 获取插槽的节点

这篇文章主要介绍了如何在vue中利用$slot 获取插槽的节点,亿速云小编觉得不错,现在分享给大家,也给大家做个参考,一起跟随亿速云小编来看看吧!

vue是什么软件

Vue是一套用于构建用户界面的渐进式JavaScript框架,Vue与其它大型框架的区别是,使用Vue可以自底向上逐层应用,其核心库只关注视图层,方便与第三方库和项目整合,且使用Vue可以采用单文件组件和Vue生态系统支持的库开发复杂的单页应用。

vue 中的 $slot

以前一直不知到这个东西,后来发现 vue api 中 藏着很多的 很神奇的 api,比如这个

如何在vue中利用$slot 获取插槽的节点

具名插槽很好理解,但是那个 default 就有点难了,

写了一个炒鸡简单的 demo

father:

<template>
<div>
<button @click="getSlot">getSlot</button>
<try ref="try">
<div class="hello1">hello1</div>
<div class="hello2">hello2</div>
<div class="hello3">hello3</div>
</try>
<button @click="getArc">getArc</button>
</div>
</template>
<script>
import try from './try'
export default {
components: {
try
},
methods: {
getSlot () {
this.$refs.try.getSlot()
}
}
}
</script>

try.vue

<template>
<div>
<h3>我是子组件 的 标题</h3>
<slot>
只有在没有内容分发的时候我才会出现
</slot>
</div>
</template>
<script>
export default {
methods: {
getSlot () {
console.log(this.$slots)
}
}
}
</script>

点击了getSlot 之后的输出

如何在vue中利用$slot 获取插槽的节点

可以看到 default ,

里面有插入的 三个 标签和 三个标签之间的 两个 空格,就有 5 个 了

通过这个就能很轻易的 拿到 父组件 通过插槽插入 子组件的 标签了

this.slotChildren = []
for (let i = 0; i< this.$slots.default.length; i++) {
if (that.$slots.default[i].elm.nodeType !== 3) {
that.slotChildren.push(that.$slots.default[i]) // 获得 那些 插入的 按钮
}
}

以上就是亿速云小编为大家收集整理的如何在vue中利用$slot 获取插槽的节点,如何觉得亿速云网站的内容还不错,欢迎将亿速云网站推荐给身边好友。