梗概
- 根据DOM元素更新响应式变量原理来更新响应式变量(一般是modelValue)的值
- 不能直接操作modelValue的值
- 官网教程:组件 v-model | Vue.js
注意
- v-model所指定的响应式变量:
Transclude of Vue-v-model命令-双向同步html数据与组件数据#^9tffhk
- 所以定义的是value,也要使用
update:modelValue
- 所以定义的是value,也要使用
新版本语法糖
<!-- Child.vue -->
<script setup>
const model = defineModel()
function update() {
model.value++
}
</script>
<template>
<div>parent bound v-model is: {{ model }}</div>
</template>旧版本: 通过计算属性
1. 实例:
<script setup>
const props = defineProps(['modelValue'])
const emit = defineEmits(['update:modelValue'])
</script>
<template>
<input
:value="props.modelValue"
@input="emit('update:modelValue', $event.target.value)"
/>
</template>2. 说明:
- child::Vue 自定义更新事件
- child::v-model指令