這一章我們將隆重介紹到的是Vue3.x被重寫的指令v-model
前言:由于在Vue2.x中,我們使用的v-model只能雙向綁定一個值,在某些需求面前顯的力不從心。但是在Vue3.x中已經(jīng)可以實現(xiàn)啦!
1、概述:數(shù)據(jù)雙向綁定
2、回顧:在Vue2.x中,v-model進行數(shù)據(jù)雙向綁定(語法糖)的原理
<my-components v-model="msg"></my-components>
// 等價于
<my-components :value="msg" @input="value=$event"></my-components>
// myComponents組件中接收綁定數(shù)據(jù)和觸發(fā)數(shù)據(jù)改變
props: { msg: String }; // 獲取數(shù)據(jù)
this.$emit("input", 'newVal'); // 觸發(fā)事件并傳值
且在Vue2.x中不能夠綁定多個v-model
3、用例:Vue3.x重寫了v-model的實現(xiàn)方式,以適用用綁定多個v-model
①:單個數(shù)據(jù)實現(xiàn)數(shù)據(jù)雙向綁定
<my-components v-model="msg"></my-components>
// 等價于
<my-components :modelValue="msg" @update:modelValue="value=$event"></my-components>
// myComponents組件中接收綁定數(shù)據(jù)和觸發(fā)數(shù)據(jù)改變
props: { modelValue: String }; // 獲取數(shù)據(jù)
setup(props, { emit }) {
emit('update:modelValue', 'newValue'); // 觸發(fā)事件并傳值
};
②:多個數(shù)據(jù)實現(xiàn)數(shù)據(jù)雙向綁定
<my-components v-model:msg="msg" v-model:name="name"></my-components>
// 等價于
<my-components :msg="msg" @update:msg="value=$event" :name="name" @update:name="name=$event"></my-components>
// myComponents組件中接收綁定數(shù)據(jù)和觸發(fā)數(shù)據(jù)改變
props: { msg: String, name: String }; // 獲取數(shù)據(jù)
setup(props, { emit }) {
emit('update:msg', 'newValue'); // 觸發(fā)事件并傳值
emit('update:name', 'newValue'); // 觸發(fā)事件并傳值
};
下一章:(十三)Vue3.x中的emits選項
上一章:(十一)template和ref獲取元素或組件實例
ps:看清現(xiàn)實!人在生前是平等的,人在死后亦是平等,唯獨人在出生后就不平等了。