Here's a common way for a subcomponent to pass values to its parent. Here is an example of addition and subtraction to explain the principle.
As shown in the figure below:
The value of the parent component is 0 when there is no operation
When the plus sign is clicked, the value of the parent component is 1
When you click the minus sign, the value of the parent component is minus one to zero
Specific code I directly paste out, just out of the code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Child component passes data to parent component</title>
<script src="https://cdn.bootcss.com/vue/2.5.17-beta.0/vue.js"></script>
</head>
<script>
//Define a component
Vue.component('counter', {
template: '\
<div style="background:#eee;width: 238px;">\
<div>This is the content of the sub components!</div>\
<div style="margin-top:20px"></div>\
<div>\
<span style="margin-right:20px;display:inline-block;">Addition operation</span><button @click="incrementCounter">+</button>\
</div>\
<div>\
<span style="margin-right:20px;margin-top:20px;display:inline-block;">Subtraction operation</span><button @click="deleteCounter">-</button>\
</div>\
</div>\
',
data: function () {
return {
counter: 0
}
},
methods: {
incrementCounter: function () {
this.counter += 1;
this.$emit('increment',1);
},
deleteCounter: function () {
this.counter -= 1;
this.$emit('increment',2);
}
}
})
//Execute a component
window.onload = function(){
var app = new Vue({
el: '#app',
data: {
total: 0
},
methods:{
incrementTotal: function (val) {
if(val==1){
this.total += 1;
}else{
if(this.total<=0){
this.total = 0;
}else{
this.total -= 1;
}
}
}
}
})
}
</script>
<body>
<div id="app" style="background:red;width: 238px;">
<p>This is the content of the parent component!</p>
<p>Values passed by subcomponents:<b>{{ total }}</b></p>
<counter v-on:increment="incrementTotal"></counter>
</div>
</body>
</html>