关于前端:自定义事件学习

1、什么是自定义事件?

    自定义事件顾名思义,就是咱们本人定义的事件,事件的名称以及回调等都由咱们本人设计实现。

2、自定义事件是干什么用的?

    自定义事件是一种组件间的通信形式,实用于子组件向父组件传值。

3、自定义事件的代码实现:

第一种形式:

父组件通过v-on定义自定义事件
v-on能够简写为@
例:v-on:demo=”send”能够写为@demo=”send”

父组件: 

App.vue:

<template>
   <div class="app">
       <h1>{{msg}}</h1>
       <TestA v-on:demo="send"/>
   </div>
</template>

<script>
import TestA from './components/TestA'
   export default {
       name:'App',
       components:{TestA},
       data(){
           return{
               msg:'自定义事件'
           }
       },
       methods:{
           send(name){
               console.log('send被调用了', name)
           },
       },
   }
</script>

子组件通过$emit向父组件传值

子组件:

TestA.vue:

<template>
    <div>
        <button @click="sendName">点击触发自定义事件</button>
      </div>
</template>

<script>
export default {
    name:'TestA',
    data(){
        return{
            name:'路飞',
            age:18
        }
    },
    methods:{
        sendName(){
            this.$emit('demo',this.name)
        }
    }
}
</script>

第二种形式:

通过ref属性拿到TestA组件组件的实例对象(vc),在组件挂载实现之后(mounted)应用this.$refs.组件名.$on(‘自定义事件名’, 回调函数)实现对子组件自定义事件的绑定

父组件: 

App.vue:

<template>
   <div class="app">
       <h1>{{msg}}</h1>
       <TestA ref="testa"/>
   </div>
</template>

<script>
import TestA from './components/TestA'
   export default {
       name:'App',
       components:{TestA},
       data(){
           return{
               msg:'自定义事件'
           }
       },
       methods:{
           send(name){
               console.log('send被调用了', name)
           }
       },
       mounted(){
           this.$refs.testa.$on('demo',this.send)
   }
</script>

子组件没有变动

子组件:

TestA.vue:

<template>
    <div>
        <button @click="sendName">点击触发自定义事件</button>
      </div>
</template>

<script>
export default {
    name:'TestA',
    data(){
        return{
            name:'路飞',
            age:18
        }
    },
    methods:{
        sendName(){
            this.$emit('demo',this.name)
        }
    }
}
</script>

一次性自定义事件:

v-on:事件名.once="XXXX"
或者
this.$refs.ref属性名.$once("事件名", 事件内容)

留神:因为是子组件向父组件传值,所以传值的动作在子组件中;父组件接管子组件的数据,所以绑定的动作在父组件中。
4、自定义事件解绑的代码实现:
父组件没有变动,子组件中通过$off解绑自定义事件

子组件:

TestA.vue:

<template>
    <div>
        <button @click="sendName">点击触发自定义事件</button>
        <button @click="noBand">解绑自定义事件</button>
      </div>
</template>

<script>
export default {
    name:'TestA',
    data(){
        return{
            name:'路飞',
            age:18
        }
    },
    methods:{
        sendName(){
            this.$emit('demo',this.name)
        },
        noBand(){
            this.$off('demo');
    }
}
</script>

留神:
如果要解绑多个事件,this.$off([“demo1”,”demo2″…]);
如果this.$off中不传递任何参数,那么此组件绑定的所有自定义事件都会解绑

总结:
自定义事件是理论开发工作中比拟罕用的办法,在进行某些操作时,应用自定义事件能够节俭开发工夫,缩小代码冗余,进步工作效率。

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理