v-model是数据双向绑定,下面用input说明:
<input type="text" v-model="price">
<input type="text" :value="price" @input="price=$event.target.value">
以上两行代码效果相同,:value 是把data里的数据绑定到input上的,但是在input里输入内容不会改变price的值,就需要用input事件监听输入的内容,改变price的值,这样就实现了数据双向绑定。
v-model的原理明白后,我们来看如何在自定义的input组件上使用v-model。
创建my-input组件,代码如下:
<template>
<div>
<input type="text" :value="price" @input="inputListener">
</div>
</template>
<script>
export default {
/**
model具体是什么意思现在不太清楚,经过测试发现,如果没有这个对象,price在本组件中是不会被同步值的。
也就是说:如果在当前组件中获取price的值是获取不到的,加上就可以了。以后明白这的原理再来完善说明。
*/
model: {
prop: "price",
event: "input"
},
props: {
price: String //这个是必须要写的,在父组件使用本组件的时候,使用v-model会自动识别value和input的事件
},
data() {
return {
};
},
components: {},
computed: {},
beforeMount() {},
mounted() {},
methods: {
inputListener: function($event) {
//发送事件到父组件,让父组件的v-model绑定的值与本组件输入的值同步
this.$emit('input', $event.target.value)
}
},
watch: {}
};
</script>
在父组件中使用
<my-input v-model="logObje.userName"></my-input>