组件自定义事件
一种组件间的通信方式, 适用于: 子组件 => 父组件
使用场景
A
是父组件, B
是子组件, B
组件需要向A
组件传递数据, 就要在A
组件中给B
组件绑定自定义事件, 事件的回调在父组件中
绑定自定义事件
方式一:
- 在父组件中给子组件实例对象绑定
show
自定义事件, 并定义事件的触发回调方法 - 子组件中通过
this.$emit('show', xxx)
向父组件中传参, 参数可多个
html
<!-- 父组件 -->
<template>
<Demo @show="getMsg" />
</template>
<script>
new Vue({
methods: {
getMsg(msg) {
console.log(msg)
}
}
})
</script>
<!-- 子组件 -->
<template>
<button @click="sendMsg">向父组件传参</button>
</template>
<script>
new Vue({
data() {
return {
msg: 'Hello World'
}
}
methods: {
sendMsg() {
this.$emit('show', this.msg)
}
}
})
</script>
方式二:
- 在父组件中通过
ref
获取子组件的实例对象, 并在mounted
生命周期中通过$on
绑定自定义事件触发函数 - 子组件中通过
this.$emit('show', xxx)
向父组件中传参, 参数可多个
html
<!-- 父组件 -->
<template>
<Demo ref="demo" />
</template>
<script>
new Vue({
mounted() {
this.$refs.demo.$on('show', this.getMsg)
},
methods: {
getMsg(msg) {
console.log('msg')
}
}
})
</script>
<!-- 子组件 -->
<template>
<button @click="sendMsg">向父组件传参</button>
</template>
<script>
new Vue({
data() {
return {
msg: 'Hello World'
}
}
methods: {
sendMsg() {
this.$emit('show', this.msg)
}
}
})
</script>
组件自定义事件扩展
若想让自定义事件只触发一次, 可以使用@show.once="getMsg"
或this.$refs.demo.$once('show', this.getMsg)
绑定方法
触发自定义事件: this.$emit('xxx', 数据)
解绑自定义事件:
- 解绑单个:
this.$off('xxx')
- 解绑多个:
this.$off(['xxx', 'yyy'])
- 解绑全部:
this.$off()
组件上也可以绑定原生DOM
事件, 需要加事件修饰符native
, 如: <Demo @click.native="xxx" />
注意
通过this.$refs.demo.$on('show', 回调)
绑定自定义事件时, 回调要么调用methods
中的方面, 要么使用箭头函数, 否则回调函数中的this
指向是组件的实例对象