# VModel
注意
用于自定义组件时,v-model prop 和事件默认名称已更改:
- prop:
value
->modelValue
- event:
input
->update:modelValue
- prop:
v-bind
的 .sync 修饰符和 组件的model
选项已移除,统一为v-model
参数形式。可以自定义
v-model
修饰符
示例:
- 默认写法
<!-- ModelComp.vue --> <template> <div @click="$emit('update:modelValue', modelValue + 1)"> {{ modelValue }} </div> </template> <script> export default { props: { modelValue: { type: Number, default: 0, }, }, } </script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17<!-- Layout.vue --> <template> <model-comp v-model="count" /> <!-- 相当于 --> <model-comp :modelValue="count" @update:modelValue="count = $event" /> </template> <script> import { ref } from 'vue' import ModelComp from './ModelComp.vue' export default { setup() { const count = ref(1) return { count } }, } </script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17- 更改 model 名称
<!-- ModelComp.vue --> <template> <div @click="$emit('update:count', count + 1)"> {{ count }} </div> </template> <script> export default { props: { count: { type: Number, default: 0, }, }, } </script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17<!-- Layout.vue --> <template> <model-comp v-model:count="count" /> <!-- 相当于 --> <model-comp :count="count" @update:count="count = $event" /> </template> <script> import { ref } from 'vue' import ModelComp from './ModelComp.vue' export default { setup() { const count = ref(1) return { count } }, } </script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
← Teleport