默认情况下,组件上的 v-model 使用 modelValue 作为 prop 和 update:modelValue 作为事件。我们可以通过向 v-model 传递参数来修改这些名称
//father.vue
<template>
<div>
{{bookTitle}}
<Child v-model:title="bookTitle" v-model:name="name"></Child>
{{name}}
</div>
</template>
<script setup>
import Child from './child'
import { ref } from 'vue'
const bookTitle = ref('hello vue3');
const name = ref('张三');
console.log(name);
</script>
子组件将需要一个 title和name prop 并发出 update:title update:name 事件来进行同步
//child.vue
<template>
<div>
<input
type="text"
:value="title"
@input="emits('update:title', $event.target.value)"
/>
<button @click="edit">修改</button>
</div>
</template>
<script setup>
import { defineProps, defineEmits } from "vue";
const emits = defineEmits(["update:title","update:name"]);
defineProps({
name: {
type: String
},
title: String,
});
const edit = () => {
//
处理数据
//
emits("update:name","李四")
}
</script>
<style></style>