vue 插槽如何内容触发组件内部事件?

定义了一个复杂的组件,里面有一个文本框和一个按钮,按钮有自定义事件,但是我希望外部使用该组件的时候,可以自定义组件的所有内容,同时能触发到组件内部按钮事件,该怎么处理呢?

us-comp 组件如下:

<slot name="reference">
    <el-input placeholder="" :value="names" :title="names" :disabled="readonly" :readonly='true' unselectable='on' class="input-with-select">
        <i slot="suffix" v-if="isShowClearButton" v-show="!readonly" @click="handleClear" class="el-input__icon el-icon-close icon-close"></i>
        <div slot='append'>
            <el-button @click="() => dialogAccessUsers = true" :disabled='readonly' style="padding: 7px 12px;" icon="el-icon-more"></el-button>
        </div>
    </el-input>
</slot>

希望外部调用可以定制里面全部内容,但是希望可以调用el-buttonclick事件

调用方:

<cus-comp>
    <el-button slot="reference">选择xxx</el-button>
</cus-comp>

希望点击 按钮选择xxx能和点击组件里面的按钮一样,谢谢!

注:不建议使用this.$refs.xxx.handleClick() 的方式来调用子组件里面的方式,这种调用比较隐蔽,子组件并不知道外部有多少调用的地方,导致不方便修改。

阅读 6.7k
1 个回答

答案如下: 参考


<!-- 伪代码:下拉框组件 us-comp -->
<template>
    <slot name="reference">
        <el-input placeholder="" :value="names" :title="names" :disabled="readonly" :readonly='true' unselectable='on' class="input-with-select">
            <i slot="suffix" v-if="isShowClearButton" v-show="!readonly" @click="handleClear" class="el-input__icon el-icon-close icon-close"></i>
            <div slot='append'>
                <el-button @click="() => dialogAccessUsers = true" :disabled='readonly' style="padding: 7px 12px;" icon="el-icon-more"></el-button>
            </div>
        </el-input>
    </slot>
<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>

调用方:

<us-comp>
    <el-button slot="reference">选择xxx</el-button>
</us-comp>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题