1:作用在表單元素上實際上就是
2:作用在自定義組件上,vue2和vue3不同
vue2:
v-model相當于名為value 的 prop和名為 input 的事件
在父組件中
<child v-model="message"></child>
//相當于:
<child :value="message" @input="function(e){message = e}"></child>
在子組件中
props:['value']
methods:{onmessage(e){$emit('input',e.target.value)}
}
vue3:
v-model默認相當于名為modelValue的 prop和名為 update:modelValue的事件
父組件中:
<child v-model="message"></child>
<child :modelValue="message" @update:modelValue="function(e){message = e}"></child>
在子組件中:
const props = defineProps({modelValue: {type: String}
})
const emit = defineEmits(["update:modelValue",
]);
const onMessage = (e) => {emit('update:modelValue', e.target.value)
}
但是也可以自定義v-model的變量名,例如
父組件中
<Child v-model:childData="childData"><p>默認插槽的內容,孩子2</p>
</Child>
子組件中
<input type="text" :value="childData" @input="onMessage($event)" />
const props = defineProps({childData: {type: String}
})
const emit = defineEmits(["update:childData",
]);
const onMessage = (e) => {emit('update:childData', e.target.value)
}