实现下图中的效果:点击子组件中的按钮实现父子组件中数据同步更新
<!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>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<style>
.parent{
width: 300px;
height: 500px;
border:1px solid #000;
background: #eee
}
.child{
width: 300px;
height: 260px;
background: #ddd
}
button{
background: greenyellow
}
</style>
</head>
<body>
<div id="app">
<v-parent class="parent"></v-parent>
</div>
<template id="parent">
<div>
<h4>我是父组件</h4>
<v-child class="child"
:wise.sync="wise"
:magic.sync="magic"
:attack.sync="attack"
:defense.sync="defense"
></v-child>
<p>智力:{{ wise }}</p>
<p>魔法:{{ magic }}</p>
<p>攻击:{{ attack }}</p>
<p>防御:{{ defense }}</p>
</div>
</template>
<template id="child">
<div>
<h4>我是子组件</h4>
<p>智力:{{ wise }}</p>
<p>魔法:{{ magic }}</p>
<p>攻击:{{ attack }}</p>
<p>防御:{{ defense }}</p>
<button @click="add('wise')">增加智力</button>
<button @click="add('magic')">增加膜法</button>
<button @click="add('attack')">增加攻击</button>
<button @click="add('defense')">增加防御</button>
<button @click="sub('wise')">减少智力</button>
<button @click="sub('magic')">减少膜法</button>
<button @click="sub('attack')">减少攻击</button>
<button @click="sub('defense')">减少防御</button>
</div>
</template>
<script>
var app=new Vue({
el:'#app',
components:{
'v-parent':{
template:'#parent',
data(){
return{
wise:90,
magic:80,
attack:95,
defense:85
}
},
components:{
'v-child':{
template:'#child',
props:{
wise:Number,
magic:Number,
attack:Number,
defense:Number
},
methods:{
add(dataName) {
let newValue = this[dataName] + 1
this.$emit(`update:${dataName}`, newValue)
},
sub(dataName){
let newValue = this[dataName] - 1
this.$emit(`update:${dataName}`, newValue)
}
}
}
}
}
}
})
</script>
</body>
</html>