您的位置:首页 > 产品设计 > UI/UE

vue2.0实现父子组件数据双向绑定

2017-09-14 11:02 821 查看
vue2.0父子组件间数据只能实现单向绑定,就是如果子组件修改了父组件传过来的data值,就会报错,

但是如果我们有这种双向绑定的需求,就要通过this.$emit暴露一个方法出去,然后由父组件决定是否调用。





【父】:

<template>
<div id="app">
父:{{ count }}
<button @click="add">+</button>
<button @click="minus">-</button>

<hello @syncCount="changeCount" :count="count"></hello>
</div>
</template>

<script>
import Hello from './components/Hello'

export default {
data() {
return {
count: 1
}
},
components: {
Hello
},
methods: {
add() {
this.count++;
},
minus() {
this.count--;
},
changeCount(val){
this.count = val;
}
}
}
</script>

<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>


【子】:

<template>
<div class="hello">
子:{{ countClone }}
<button @click="add">+</button>
<button @click="minus">-</button>
</div>
</template>

<script>
export default {
props: {
count: {
type: Number
}
},
data() {
return {
countClone: this.count
}
},
watch: {
count(val) {
this.countClone = val;
},
countClone(val){
this.$emit('syncCount',val);
}
},
methods: {
add() {
this.countClone++;
},
minus() {
this.countClone--;
}
}
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1,
h2 {
font-weight: normal;
}

ul {
list-style-type: none;
padding: 0;
}

li {
display: inline-block;
margin: 0 10px;
}

a {
color: #42b983;
}
</style>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: