009 自定义事件组件交互
自定义事件组件交互(可以理解成数据的反向传递)
自定义事件可以在组件中反向传递数据,PROP可以将数据从父组件传递到子组件,那么反向如何操作呢,就可以利用自定义事件实现$emit
<template>
<h3>单文件组件</h3>
<button @click="sendHandle">发送数据</button>
</teplate>
<script>
export default {
name:"MyComponent",
methods:{
sendHandle(){
this.$emit("onCustom","数据")
}
}
}
</script>
<style scooped>
h3{
color:red;
}
</style>
<template>
<my-componentVue @onCustom="getData"/>
</template>
<script>
import MyComponentVue from'./components/MyComponent.vue'
export default{
name:'App',
components:{
MyComponentVue
},
methdos:{
getData(data){
console.log(data);
}
}
}
</spript>


一、子组件中:
1、先准备数据:
data(){
return{
message:"我是数据"
}
要写在script 里面的export default里面。
2、需要一个事件来触发他
<button @click="sendClickHandle">点击传递</button>
要写在template中
3、承载这个事件
methods:{
sendClickHandle(){
//参数1:字符串:理论上是随便的,但是需要具有意义
//参数2:传递的数据
this.$emit("onEvent(自定义事件名字)",this.message)
}
}
二、父组件中:
1、在这里监听着,就可以实现了
<组件名字 @onEvent(自定义事件名字)="getDataHandle(这是个函数,一样把他当作事件来看待)"> 要写在template中
2、需要methods来接收这个函数
methods:{
getDataHandle(data(数据参数在这)){
console.log(data);
}
}
要写到script中。
这时候数据就被打印出来了。
3、要显示到页面上来也可以,页面中所有的数据都依赖于data来帮你进行显示。
data(){
return{
message:""
}
}
要写到export default中。
<p>{{ message }} </p>
要写在template中。
修改:
methods:{
getDataHandle(data(数据参数在这)){
console.log(data);改成:this.message=data;(把传递过来的数据,赋值给message)
}
}

浙公网安备 33010602011771号