父组件中的状态发生改变,子组件中的状态同步发生改变。
处于同一父组件中的兄弟节点之间如何同步状态。
留意watch,这是要点:父组件向子组件传递的属性发生改变时,子组件如何同步。
<template>
<div>
<Man v-on:beliefChange="beliefChange" v-bind:belief="belief"></Man>
<Woman v-on:beliefChange="beliefChange" v-bind:belief="belief"></Woman>
<input v-model="belief"/>
</div>
</template>
<script>
import Man from './Man';
import Woman from './Woman';
export default {
name: 'Person',
components: {Man, Woman},
data() {
return {
belief: 'image'
}
},
methods: {
beliefChange(newBelief) {
this.belief = newBelief;
console.log('this.belief', this.belief);
}
},
}
</script>
<style scoped>
</style>
<template>
<div>
<input v-model="value" v-on:change="changeValue" />
</div>
</template>
<script>
export default {
name: 'Man',
props: ['belief'],
data() {
return {
value: this.belief
}
},
methods: {
changeValue() {
this.$emit('beliefChange', this.value);
}
},
watch: {
belief: function(newValue, oldValue) {
this.value = newValue;
}
},
}
</script>
<style scoped>
</style>
<template>
<div>
<input v-model="value" v-on:change="changeValue" />
</div>
</template>
<script>
export default {
name: 'Woman',
props: ['belief'],
data() {
return {
value: this.belief
}
},
methods: {
changeValue() {
this.$emit('beliefChange', this.value);
}
},
watch: {
belief: function(newValue, oldValue) {
this.value = newValue;
}
},
}
</script>
<style scoped>
</style>