[ Vue ] 给 slot 插槽绑定事件

最近写了一个下拉组件,希望任意形式的触发源点击都可以展开这个组件。

最终效果图如下:

方案一:slot-scope 传方法

<!-- 伪代码:下拉框组件 -->

<template>
    <slot change-display="changeDisplay"></slot>
    <div v-show="mVisiable">*下拉框代码省略*<div>
<template>

<script>
export default {
    data(){
        return {
            mVisiable: false
        }
    }

    methods:{
        changeDisplay(){
            this.mVisiable = !this.mVisiable
        }
    }
}
</script>
<!--使用下拉弹窗组件-->
<dropdown v-model="value" :list="list">
      <button slot-scope="{changeDisplay}" 
        @click="changeDisplay">{{value}}</button>
</dropdown>

不过这就导致每次用插槽都要写 slot-scope 去取修改显示状态的函数。

方案二:找 VNode 中对应的页面元素

插曲:

<!-- 伪代码:下拉框组件 -->
<template>
    <slot></slot>
    <div v-show="mVisiable">*下拉框代码省略*<div>
<template>

<script>
export default {
    data(){
        return {
            mVisiable: false
        }
    }

    methods:{
        changeDisplay(){
            this.mVisiable = !this.mVisiable
        }
    }

    mounted() {
      console.log(this.$slots)
    }
}
</script>


<!--使用下拉弹窗组件-->
<dropdown v-model="value" :list="list">
  <template v-slot>
    <button>{{value}}</button>
  </template>
</dropdown>

根据vue文档 slot 被废弃了(但还是兼容的)使用 v-slot 指定插槽,但是输出VNode 中的 elm 是 undefined。

然后去查找 github vue issues 找到如下回答, 传送门: issue

最后换回旧的插槽方法

<!--使用下拉弹窗组件-->
<dropdown v-model="value" :list="list">
    <button>{{value}}</button>
</dropdown>

此时得到了插槽内的元素


修改下拉组件。为VNode中的elm增加点击事件。

<!-- 伪代码:下拉框组件 -->
<template>
    <slot></slot>
    <div v-show="mVisiable">*下拉框代码省略*<div>
<template>

<script>
export default {
    data(){
        return {
            mVisiable: false
            reference: undefined
        }
    }

    methods:{
        changeDisplay(){
            this.mVisiable = !this.mVisiable
        }
    }

    mounted() {
        if (this.$slots.default) {
          this.reference = this.$slots.default[0].elm
        }
        if (this.reference) {
          this.reference.addEventListener('click', this.changeVisiable, false)
        }
    }

    beforeDestroy() {
        if (this.reference) {
          this.reference.removeEventListener('click', this.changeVisiable, false)
        }
    }
}
</script>

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章