vue2比較讓人詬病的一點就是提供了兩種雙向綁定:v-model和.sync,
在vue3中,去掉了.sync修飾符,只需要使用v-model進行雙向綁定即可。
為了讓v-model更好的針對多個屬性進行雙向綁定(vue2中自定義組件中v-model只能使用一次),vue3做出了以下修改:
1、當對自定義組件使用v-model指令時,綁定的屬性名由原來的value變?yōu)閙odelValue,事件名由原來的input變?yōu)閡pdate:modelValue:
<!-- vue2 -->
<ChildComponent :value="pageTitle" @input="pageTitle = $event" />
<!-- 簡寫為 -->
<ChildComponent v-model="pageTitle" />
<!-- vue3 -->
<ChildComponent
:modelValue="pageTitle"
@update:modelValue="pageTitle = $event"
/>
<!-- 簡寫為 -->
<ChildComponent v-model="pageTitle" />
vue3中子組件,關鍵代碼文章來源地址http://www.zghlxwxcb.cn/news/detail-812978.html
// 接受的屬性值
let props = defineProps({
modelValue:{
type:String,
default:'',
}
});
// 觸發(fā)方法
emits('update:modelValue','newValue')
去掉了.sync修飾符,它原本的功能由v-model的參數(shù)替代:
<!-- vue2 -->
<ChildComponent :title="pageTitle" @update:title="pageTitle = $event" />
<!-- 簡寫為 -->
<ChildComponent :title.sync="pageTitle" />
<!-- vue3 -->
<ChildComponent :title="pageTitle" @update:title="pageTitle = $event" />
<!-- 簡寫為 -->
<ChildComponent v-model:title="pageTitle" />
不要蒙圈,相當于在vue3中,v-model不加參數(shù)的情況就相當于給子組件傳遞了modelValue這個屬性,除了這個屬性外其余的都要加參數(shù)。文章來源:http://www.zghlxwxcb.cn/news/detail-812978.html
vue3中子組件,關鍵代碼
// 接受的屬性值
let props = defineProps({
title:{
type:String,
default:'',
}
});
// 觸發(fā)方法使用'update:參數(shù)'
emits('update:title','newValue')
到了這里,關于vue3中l(wèi)和vue2中v-model不同點的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!