vue使用v-model实现父子组件间通信
Vue官方文档提到父子组件之间的通信方式:
- 父组件到子组件:通过
props
传递数据; - 子组件到父组件:通过自定义事件实现;
使用
props
和自定义事件的方法按照官方所说的方式,我们写一个demo:点击父组件中的按钮数值加5,点击子组件中的按钮数值减5。 父组件:
<template>
<div>
<child :total="total" v-on:reduce="reduce"></child>
<button @click="increse">增加5</button>
</div>
</template>
<script>
import Child from "./child.vue"
export default {
components: {
Child
},
data: function () {
return {
total: 0
};
},
methods: {
increse: function () {
this.total += 5;
},
reduce: function (v) {
this.total -= v;
}
}
}
</script>
子组件child.vue:
<template>
<div>
<span>{{total}}</span>
<button @click="reduce">减少5</button>
</div>
</template>
<script>
export default {
props: {
total: Number
},
methods: {
reduce: function(){
this.$emit("reduce", 5)
}
}
}
</script>
这种方式需要在父组件中添加一个reduce
方法,并且需要在<child>
标签上添加v-on:reduce
监听事件,方式有点繁琐。
使用
v-model
实现的方法下面介绍一下如何使用v-model
来实现父子组件间的通信(其实原理还是和上面一样)。
父组件:
<template>
<div>
<child v-model="total"></child>
<button @click="increse">增加5</button>
</div>
</template>
<script>
import Child from "./child.vue"
export default {
components: {
Child
},
data: function () {
return {
total: 0
};
},
methods: {
increse: function () {
this.total += 5;
}
}
}
</script>
子组件child.vue:
<template>
<div>
<span>{{value}}</span>
<button @click="reduce">减少5</button>
</div>
</template>
<script>
export default {
props: {
value: Number // 注意这里是value
},
methods: {
reduce: function(){
this.$emit("input", this.value - 5)
}
}
}
</script>
这样是不是简单许多?
如果把<input v-model="total">
理解成<input v-on:input="total=arguments[0]" :value="total">
就容易懂了。