Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.7k views
in Technique[技术] by (71.8m points)

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() 的方式来调用子组件里面的方式,这种调用比较隐蔽,子组件并不知道外部有多少调用的地方,导致不方便修改。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

答案如下: 参考


<!-- 伪代码:下拉框组件 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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...