组件v-model(.sync)记录使用(vue3)
warning:
这篇文章距离上次修改已过429天,其中的内容可能已经有所变动。
在Vue 3中,v-model是一个指令,它创建了一个双向绑定,用于在子组件和父组件之间同步数据。.sync修饰符允许你在父组件中直接修改子组件的props,而不需要显式地发出事件。
以下是一个简单的例子,展示了如何使用v-model和.sync:
<!-- 子组件 -->
<template>
<input :value="modelValue" @input="$emit('update:modelValue', $event.target.value)">
</template>
<script>
export default {
props: {
modelValue: String,
},
emits: ['update:modelValue'],
};
</script>
<!-- 父组件 -->
<template>
<ChildComponent v-model="parentData" />
</template>
<script>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent,
},
setup() {
const parentData = ref('');
return { parentData };
},
};
</script>如果你想要使用.sync修饰符,子组件的props需要以modelValue和update:modelValue命名,父组件中则直接使用v-model.sync来创建双向绑定。
<!-- 子组件 -->
<template>
<input :value="modelValue" @input="$emit('update:modelValue', $event.target.value)">
</template>
<script>
export default {
props: {
modelValue: String,
},
emits: ['update:modelValue'],
};
</script>
<!-- 父组件 -->
<template>
<ChildComponent v-model.sync="parentData" />
</template>
<script>
import { ref } from 'vue';
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent,
},
setup() {
const parentData = ref('');
return { parentData };
},
};
</script>在这个例子中,v-model.sync允许你直接在父组件中修改parentData的值,而不需要显式地通过事件来更新它。
评论已关闭