Vue cli engineering subcomponent transfers value to parent component
Posted by sitestem on Sat, 28 Mar 2020 15:46:20 +0100
When the child communicates with the parent component, you need to use a custom event. Use v-on:xxx or @: xxx. In addition to listening for DOM events,
It can also be used for custom events between components
The child uses $emit() to trigger the event the parent uses $on() to listen for the child's event
--------------------------------------
In addition to using v-on | @ to add custom events on components, you can also listen to DOM events. In this case, you need to use the. Navive modifier
Indicates listening to a native event, listening to the root element of the component
The code is as follows:
<three :outdata="a" @click.native="changeA"/>
Parent component template
<template>
<div id="app">
{{ a }}
<three :outdata="a" @changeNew="changeA"/>
</div>
</template>
<script>
import three from './components/three'
export default {
components:{
three
},
data(){
return {
a:"I am the value of the parent component"
}
},
methods:{
changeA(event){
this.a = event
}
}
}
</script>
Subcomponent template
-------
<template>
<div class="three">
{{ outdata }}
<br>
<button @click="change">Change the value of the parent component</button>
</div>
</template>
<script>
export default {
props:{
outdata:{
type:String,
default:''
}
},
data(){
return{
}
},
methods:{
change(){
this.$emit('changeNew',"I was changed!")
}
}
}
</script>
The second way is to use the v-model instruction on the child component
Parent component template
-----
<template>
<div id="app">
{{ a }}
<three :outdata="a" v-model="a"/>
</div>
</template>
<script>
import three from './components/three'
export default {
components:{
three
},
data(){
return {
a:"I am the value of the parent component"
}
},
methods:{
changeA(event){
this.a = event
}
}
}
</script>
Subcomponent template
-----
<template>
<div class="three">
{{ outdata }}
<br>
<button @click="change">Change the value of the parent component</button>
</div>
</template>
<script>
export default {
props:{
outdata:{
type:String,
default:''
}
},
data(){
return{
}
},
methods:{
change(){
this.$emit('input',"I was changed!")
}
}
}
</script>