美文网首页
(十二)Vue3.x中重写的v-model

(十二)Vue3.x中重写的v-model

作者: Mr_莫言之 | 来源:发表于2020-10-22 09:21 被阅读0次
这一章我们将隆重介绍到的是Vue3.x被重写的指令v-model

前言:由于在Vue2.x中,我们使用的v-model只能双向绑定一个值,在某些需求面前显的力不从心。但是在Vue3.x中已经可以实现啦!
1、概述:数据双向绑定
2、回顾:在Vue2.x中,v-model进行数据双向绑定(语法糖)的原理

<my-components v-model="msg"></my-components>
// 等价于
<my-components :value="msg" @input="value=$event"></my-components>

// myComponents组件中接收绑定数据和触发数据改变
props: { msg: String }; // 获取数据
this.$emit("input", 'newVal'); // 触发事件并传值

且在Vue2.x中不能够绑定多个v-model
3、用例:Vue3.x重写了v-model的实现方式,以适用用绑定多个v-model
①:单个数据实现数据双向绑定

<my-components v-model="msg"></my-components>
// 等价于
<my-components :modelValue="msg" @update:modelValue="value=$event"></my-components>

// myComponents组件中接收绑定数据和触发数据改变
props: { modelValue: String }; // 获取数据
setup(props, { emit }) {
    emit('update:modelValue', 'newValue'); // 触发事件并传值
};

②:多个数据实现数据双向绑定

<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组件中接收绑定数据和触发数据改变
props: { msg: String, name: String }; // 获取数据
setup(props, { emit }) {
    emit('update:msg', 'newValue'); // 触发事件并传值
    emit('update:name', 'newValue'); // 触发事件并传值
};

下一章:(十三)Vue3.x中的emits选项
上一章:(十一)template和ref获取元素或组件实例

ps:看清现实!人在生前是平等的,人在死后亦是平等,唯独人在出生后就不平等了。

相关文章

网友评论

      本文标题:(十二)Vue3.x中重写的v-model

      本文链接:https://www.haomeiwen.com/subject/inrnpktx.html