组件的自定义事件
-
一种组件间通信的方式,适用于:子组件 ===> 父组件 -
使用场景:A是父组件,B是子组件,B想给A传数据,那么就要在A中给B绑定自定义事件(事件的回调在A中)。 -
绑定自定义事件:
-
第一种方式,在父组件中:<Demo @atguigu="test"/> ?或?<Demo v-on:atguigu="test"/> -
第二种方式,在父组件中: <Demo ref="demo"/> ...... mounted(){ this.$refs.xxx.$on('atguigu',this.test) } -
若想让自定义事件只能触发一次,可以使用once 修饰符,或$once 方法。
-
触发自定义事件:this.$emit('atguigu',数据) -
解绑自定义事件this.$off('atguigu') -
组件上也可以绑定原生DOM事件,需要使用native 修饰符。 -
注意:通过this.$refs.xxx.$on('atguigu',回调) 绑定自定义事件时,回调要么配置在methods中,要么用箭头函数,否则this指向会出问题!
代码演示?
//父组件代码
<template>
<div>
<h1>当前年龄为{{age}}</h1>
<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第一种写法,使用@或v-on) -->
<!-- <Son @addAge="add"/> -->
<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第二种写法,使用ref) -->
<Son ref="sonComponents"/>
</div>
</template>
<script>
import Son from './components/Son.vue'
export default {
name: 'App',
data() {
return {
age: 18
}
},
components: {
Son
},
methods: {
add (age) {
this.age += age
}
},
mounted() {
this.$refs.sonComponents.$on("addAge", this.add) //绑定自定义事件
// this.$refs.sonComponents.$once("addAge", this.add) //绑定自定义事件 once一次性
},
}
</script>
<style>
</style>
//子组件代码
<template>
<div class="son">
<p>我是子组件</p>
<button @click="demo">点击加1</button>
<button @click="unbind">解绑自定义事件</button>
</div>
</template>
<script>
export default {
name:'Son',
data() {
return {
number: 1
}
},
methods: {
demo() {
//触发Son组件实例身上的addAge事件
this.$emit('addAge', this.number)
},
unbind() {
this.$off('addAge') // 解绑一个事件 解绑多个事件传递一个数组["xxxx", "xxxx"]
// this.$off() // 解绑所有事件
}
},
}
</script>
<style scoped>
.son{
background-color: skyblue;
padding: 5px;
}
</style>
|