天天看點

vue3的自定義事件傳參

子元件中

點選<li>,傳輸目前列的資料,目前<li>綁定click事件,把需要傳輸的參數作為click事件的參數。

<ui>
    <li  ref="groupRef" v-for="item in group.list" :key="item.id" class="item"
        @click="singerDetail(item.mid)"
    >
        <span class="avatar" >
            <el-image :src="item.pic" lazy  />
        </span>
        <a class="name">{{item.name}}</a>
    </li>
    <el-divider style="width: 100%" border-style="dashed" />
</ui>
           

在<script>标簽體中定義emits,emits的定義是與component、setup等這些屬性是同級

emits:['select', 'xxx'],
           

在setup( )中實作click事件,綁定自定義事件(注意:setup()的參數需要 props 和 { emit } )

setup(props,{ emit }) {
    const singerDetail = item => {
        emit('select', item)
        // console.log('item = ' + item)
    }

    return{
        singerDetail
    }
}
           

完整<script>代碼:

vue3的自定義事件傳參

 父元件中

vue3的自定義事件傳參

 在需要使用的元件中實作自定義函數,let一個值接收參數,

selectSinger(singer){
    let mySelectSinger = singer;
    // console.log('mySelectSinger= ' + mySelectSinger)
    this.$router.push({
        name: 'singerDetail',
        params:{
            mySelectSinger : mySelectSinger
        }
    })
}
           

繼續閱讀