您的位置:首页 > 产品设计 > UI/UE

vue 中的 $slot 获取 插槽的节点

2018-03-12 16:08 1621 查看
vue 中的 $slot
以前一直不知到这个东西,后来发现 vue api 中 藏着很多的 很神奇的 api,比如这个



具名插槽很好理解,但是那个 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> <h2>我是子组件 的 标题</h2> <slot> 只有在没有内容分发的时候我才会出现 </slot> </div></template><script>export default { methods: { getSlot () { console.log(this.$slots) } }}</script>

点击了getSlot 之后的输出



可以看到 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 节点