- 2018-07-03 創(chuàng)建
父子雙向數(shù)據(jù)綁定
- 父組件改變數(shù)據(jù)可以改變子組件, 但是子組件的內(nèi)容改變并不會(huì)影響到父組
- 可以通過(guò)2.3.0新增的sync修飾符來(lái)達(dá)到雙向綁定的效果
example
father.vue
<template>
<div class="hello">
//input實(shí)時(shí)改變wrd的值, 并且會(huì)實(shí)時(shí)改變box里的內(nèi)容
<input type="text" v-model="wrd">
<box :word.sync="wrd" ></box>
</div>
</template>
<script>
import box from './box' //引入box子組件
export default {
name: 'HelloWorld',
data() {
return {
wrd: ''
}
},
components: {
box
}
}
</script>
<style scoped>
</style>
box.vue
<template>
<div class="hello">
<div class="ipt">
<input type="text" v-model="str">
</div>
//word是父元素傳過(guò)來(lái)的
<h2>{{ word }}</h2>
</div>
</template>
<script>
export default {
name: 'box',
data() {
return {
str: '',
}
},
props: {
word: ''
},
watch: {
str: function(newValue, oldValue) {
//每當(dāng)str的值改變則發(fā)送事件update:word , 并且把值傳過(guò)去
this.$emit('update:word', newValue)
}
}
}
</script>
<style scoped>
</style>
原理
- 利用了父級(jí)可以在子元素上監(jiān)聽(tīng)子元素的事件
father.vue
<template>
<div class="hello">
<input type="text" v-model="wrd">
<box @incre="boxIncremend" ></box>
</div>
</template>
<script>
import box from './box'
export default {
name: 'HelloWorld',
data() {
return {
wrd: ''
}
},
methods: {
boxIncremend(e) {
this.wrd = this.wrd + e
}
},
components: {
box
}
}
</script>
<style scoped>
</style>
box.vue
<template>
<div class="hello">
<input type="text" v-model="str">
<h2>{{ word }}</h2>
</div>
</template>
<script>
export default {
name: 'box',
data() {
return {
num: 0
}
},
props: {
word: ''
},
watch: {
str: function(neww, old) {
//往父級(jí)發(fā)射incre事件
this.$emit('incre', ++this.num)
}
},
}
</script>
<style scoped>
</style>