组件的自定义事件

vue2中组件间的通信方式,通常用于子组件传递数据给父组件。

1、父组件的写法

①用v-on或@

<template>
    <div class="app">
        <h1>收到Demo组件的sth:{{msg}}</h1>
        <Demo v-on:demo="receiveSthFromDemo"/>
    </div>
</template>
<script>
    import Demo from './components/Demo'
    export default {
        name:'App',
        components:{Demo},
        data() {
            return {
                msg:''
            }
        },
        methods: {
            receiveSthFromDemo(data){
                console.log('我是App组件,我收到了来自Demo组件的数据:'+data)
                this.msg = data
            }
        },
    }
</script>
<style>
    .app{
        background-color: skyblue;
    }
</style>

②用ref

<Demo ref="ect"/>
        ......
mounted(){
    this.$refs.ect.$on('demo',this.receiveSthFromDemo)
}

2、子组件的写法

<template>
    <div class="demo">
        <button @click="sendSthToApp">点击发送sth给App组件</button>
        <button @click="unbind">点击解绑demo事件</button>
    </div>
</template>
<script>
    export default {
        name:'Demo',
        data() {
            return {
                sth:'我是sth'
            }
        },
        methods: {
            sendSthToApp(){
                this.$emit('demo',this.sth)
            },
            unbind(){
                this.$off('demo')
            }
        },
    }
</script>
<style>
    .demo{
        background-color: pink;
    }
</style>

3、解绑自定义事件

this.$off('demo')

注:若this.$off()中不传参,则默认解绑所有事件。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值