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()中不传参,则默认解绑所有事件。