先看下简单的,在一个页面中使用 v-model 进行 双向数据绑定:
<input type="text" v-model="textValue">
<h1>{{ textValue }}</h1>
相信这行代码,大家肯定都非常熟悉!官方文档说明了 v-model 其实如如下原理:
<input type="text"
v-bind:value = "textValue"
v-on:input = "textValue = $event.target.value"
>
<h1>{{ textValue }}</h1>
组件上使用v-model:
//父组件 templateParant.vue
<template>
<div>
<template-child v-model="textValue"></template-child>
<!-- <template-child
v-bind:value = "textValue"
v-on:input = "textValue = $event"
></template-child> -->
<!-- 这两种写法是等价的,至于 v-on:input = "textValue = $event"
为什么是 $event而不是$event.target.value,这是一个值得思考的问题 -->
<div>{{ textValue }}</div>
</div>
</template>
<script>
import templateChild from './templateChild '
export default {
data() {
return {
textValue: ''
}
},
components: {
modelChild
},
mounted() {
}
};
</script>
<style scoped>
</style>
// 子组件templateChild.vue
<template>
<div>
输入<input type="text"
v-bind:value="value"
v-on:input="$emit('input',$event.target.value)"
>
</div>
</template>
<script>
export default {
props: ['value'], //子组件用一个props接住父组件传进来的value属性值,然后在自己的input绑定该值,并且使用$emit向父组件通信,传递input事件和input输入的值($event.target.value),在父组件v-model既可以实现与子组件的双向数据绑定了。
data() {},
components: {
},
mounted() {
}
};
</script>
<style scoped>
</style>