企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
>[success] # v-model 组件 1. 在`input`中可以使用`v-model`来完成**双向绑定**,组件也可以使用`v-model`形式进行双向绑定和` vue2.x` 时候只能定义一个,因此往往使用`.sync` 语法糖进行多个绑定,在`vue3.x` 开始,`v-model` 用法也升级了可以进行多个绑定,因此`.sync`语法糖也在3移除 2. 在组件使用`v-model`他的语法糖 需要定义的`props `属性名 `modelValue` 触发抛出的事件名`update:modelValue` ~~~ html <input v-model="searchText" /> <!--等价于:--> <input :value="searchText" @input="searchText = $event.target.value" /> ~~~ ~~~html <custom-input v-model="searchText" /> <!--等价于:--> <custom-input :model-value="searchText" @update:model-value="searchText = $event" ></custom-input> ~~~ * CustomInput 组件 定义 ~~~html <!-- CustomInput.vue --> <script> export default { props: ['modelValue'], emits: ['update:modelValue'] } </script> <template> <input :value="modelValue" @input="$emit('update:modelValue', $event.target.value)" /> </template> ~~~ **通过案例对比看也就`value` => `model-value`,`input` => ` @update:model-value`** >[danger] ##### 在对比来看不用v-model 语法糖来写 ~~~ 1. 案例就是常见的,父组件传值给子组件,子组件触发事件改变父组件值,从而达到改变子组件值 ~~~ * 父 ~~~ <template> <children-todo :model-value="name" @update:model-value="name = $event"> </children-todo> </template> <script> import childrenTodo from './components/children-todo.vue' export default { name: 'App', components: { childrenTodo, }, data() { return { name: '父组件', } }, } </script> <style></style> ~~~ * 子 ~~~ <template> <div class="content"> {{ modelValue }} <button @click="change">改变</button> </div> </template> <script> export default { props: ['modelValue'], emits: ['update:modelValue'], methods: { change() { this.$emit('update:modelValue', '1', '2') }, }, } </script> ~~~ >[danger] ##### 绑定多个v-model 1. 原来`2.x`由于 `v-model` 在一个组件只能出现一次,因此出现了使用`.sync`语法糖来弥补这个问题,现在`3.x`的`v-model `支持绑定多个因此`.sync` 也不在支持 2. 用法只要声明`v-model` 所属即可,`v-model:名字` 例如 组件默认的`v-model` 其实是`v-model:modelValue` 的缩写因此在子组件接受时候`props` 为`props: ['modelValue']` , 事件为`emits: ['update:modelValue']`,那如果绑定值定义如下`v-model:title` 则`props: ['title']` ,`emits: ['update:title']` * 父 ~~~html <template> <children-todo v-model="name" v-model:title="title"> </children-todo> </template> <script> import childrenTodo from './components/children-todo.vue' export default { name: 'App', components: { childrenTodo, }, data() { return { title: '父组件标题', name: '父组件', } }, } </script> <style></style> ~~~ * 子 ~~~html <template> <div class="content"> {{ modelValue }} {{ title }} <button @click="change">改变</button> </div> </template> <script> export default { props: ['modelValue', 'title'], emits: ['update:modelValue', 'update:title'], methods: { change() { this.$emit('update:modelValue', '1') this.$emit('update:title', 'title') }, }, } </script> <style scoped> .content { display: flex; } .left, .right { width: 80px; } .left, .right, .center { height: 44px; } .left, .right { width: 80px; background-color: red; } .center { flex: 1; background-color: blue; } </style> ~~~ >[info] ## 官方 [配合 v-model 使用](https://cn.vuejs.org/guide/components/events.html#usage-with-v-model)