1.介绍
在组件标签中使用v-model属性可以实现父子组件中表单控件中数据的一致,就像表单控件中的v-model,数据不仅能从data(模型)流向页面(视图),还可以从页面流向data。总的来说就四个字:实现数据的双向绑定
2.vue2中使用
//父组件
//<template>中:
<CountBox v-model="Count"></CountBox>
//上面代码相当于:
//<CountBox :value="Count" @input="(val)=>{ Count=val}"></CountBox>
//<script>中:
export default {
components: {
CountBox
},
data () {
return {
Count: 1,
}
},
//子组件
//<template>中:
<input :value="value" @blur="changeHandle" >
//<script>中:
export default {
props: {
value: {
type: Number
}
},
methods: {
changeHandle (e) {
this.$emit('input', e.target.value)
}
}
}
上面代码的解释:
父组件在使用子组件的时候给子组件配置v-model,既给子组件传递了数据(Count),又绑定了input自定义事件(@input)
子组件通过 props接收value(Count),并利用输入框身上的@blur事件监听输入框失去焦点,输入框失去焦点的时候会触发事件的回调,事件的回调changeHandle中通过 this.$emit 触发父组件的input 自定义事件,并传递用户输入的值作为参数
这样就实现了数据在父子组件中的双向绑定
3.vue3中使用
vue3中组件标签中的v-model动态绑定的变量不是value,而是modelValue,绑定的自定义事件由@input改为@update:modelValue。
//父组件
<template>
<child v-model="msg" />
<p>{{msg}}</p>
</template>
<script lang="ts">
import { defineComponent,ref} from 'vue';
import child from './components/child/index.vue'
export default defineComponent({
name: 'App',
components:{
child
},
setup(){
const msg = ref('1')
return{
msg
}
}
});
</script>
//子组件
<template>
<input type="text" :value="modelValue" @input="onInput">
</template>
<script lang="ts">
import {defineComponent} from 'vue'
export default defineComponent({
name:'ChildInput',
props:{
modelValue:{
type:String
}
},
setup(){
const onInput = (e) =>{
context.emit('update:modelValue',e.target.value)
}
return{
onInput
}
}
})
</script>