要使子组件修改 v-model 的值时,父组件也能感知到变化,你需要在子组件中实现对 v-model 的支持。v-model 在 Vue 中实际上是语法糖,它会将 v-model 绑定的属性和 input 事件结合起来。
以下是如何在子组件中实现对 v-model 的支持的步骤:
定义 v-model 绑定的属性:在子组件中,定义一个 props 用于接收 v-model 的值。
触发 input 事件:在子组件中,当需要更新值时,触发 input 事件来通知父组件值已更改。
以下是一个简单的示例:
父组件
<template>
<div>
<test v-model="count"></test>
<div class="card">
<button type="button" @click="count++">count is {{ count }}</button>
</div>
</div>
</template>
<script>
import Test from './Test.vue';
export default {
components: { Test },
data() {
return {
count: 0
};
}
};
</script>
子组件(Test.vue)
<template>
<div>
<button @click="increment">Increment</button>
</div>
</template>
<script>
export default {
props: {
modelValue: Number
},
methods: {
increment() {
this.$emit('update:modelValue', this.modelValue + 1);
}
}
};
</script>
说明:
在子组件中,我们定义了一个 modelValue 的 prop,它是 v-model 绑定的值。
当我们在子组件中执行 increment 方法时,我们通过 this.$emit(‘update:modelValue’, newValue) 触发了一个 update:modelValue 事件,这样父组件才能接收到子组件中 modelValue 的更新。
在 Vue 3 中,v-model 默认使用 modelValue 作为 prop 名称和 update:modelValue 作为事件名称。
vue3用法
父组件
<template>
<div>
<Test v-model:count="count" />
<div class="card">
<button type="button" @click="count++">count is {{ count }}</button>
</div>
</div>
</template>
<script>
import { ref } from 'vue';
import Test from './Test.vue';
export default {
components: { Test },
setup() {
const count = ref(0);
return {
count
};
}
};
</script>
子组件:
<template>
<div>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { defineComponent, toRefs } from 'vue';
export default defineComponent({
props: {
modelValue: {
type: Number,
default: 0
}
},
emits: ['update:modelValue'],
setup(props, { emit }) {
const { modelValue } = toRefs(props);
function increment() {
emit('update:modelValue', modelValue.value + 1);
}
return {
increment
};
}
});
</script>