The parent component uses props to pass data (such as a method) to the child component, and the child component needs to use custom events to pass data back to the parent component! We can use v-on to bind custom events, and then pass them to subcomponents, which will call after receiving the method. Each Vue instance implements the Events interface, that is: use $on(eventName) to listen for events and $emit(eventName) to trigger events.
Ways to use props
//App.vue
<template>
<div>
<Son :sendToSon="sendToSon"></Son>
</div>
</template>
methods: {
sendToSon(prams){
console.log(prams)
}
},
//Son.Vue
<template>
<div>
<button @click="sendToFather">Send</button>
</div>
</template>
<script>
export default {
name:"Son",
props:["sendToSon"],
data () {
return {
name: 'hello!!!'
}
},
methods: {
sendToFather(){
this.sendToSon(this.name)
}
},
}
</script>
Use the ref attribute to complete
//App.vue
<template>
<div>
<Son ref="son"></Son>
</div>
</template>
methods: {
sendToSon(prams){
console.log(prams)
}
},
mounted() {
setTimeout(()=>{
this.$refs.son.$on("fun1",this.sendToSon)
},2000)
}
//Son.vue
<template>
<div>
<button @click="sendToFather">Send</button>
</div>
</template>
<script>
export default {
name:"Son",
data () {
return {
name: 'hello!!!'
}
},
methods: {
sendToFather(){
this.$(emit)("fun1",this.name)
}
},
}
</script>
Comments
Post a Comment