vue3.0中 v-model 是 modelValue 和 update:modelValue 的语法糖
父组件:v-model 绑定的是引用类型
<template>
<div id="nav">
<!-- 子组件上绑定 v-model -->
<son v-model="person" />
<p>我是父亲的:{{ person.name }}</p>
<button @click="handleClick">我是父亲的按钮</button>
</div>
</template>
<script>
import Son from "@/components/son";
import { reactive } from "@vue/reactivity";
export default {
components: { Son },
setup() {
const person = reactive({
name: "zs",
});
const handleClick = () => {
person.name = "ls";
};
return { person, handleClick };
},
};
</script>
子组件
<template>
<div>
<!-- 子组件内使用 modelValue -->
<p>我是son的:{{ modelValue }}</p>
<button @click="handleFn">我是son的按钮</button>
</div>
</template>
<script>
import { useVModel } from "@vueuse/core";
export default {
// 子组件接收 modelValue
props: {
modelValue: {
type: Object,
},
},
setup(props, { emit }) {
// useVModel 解析 modelValue 的值
const obj = useVModel(props, "modelValue", emit); //相当于 emit("update:modelValue", "zzzzz");
const handleFn = () => {
//更新 modelValue 的值
obj.value.name = "zzzz";
};
return { handleFn };
},
};
</script>
父组件:v-model 绑定的是基本类型
<template>
<div id="nav">
<!-- 子组件上绑定 v-model -->
<son v-model="info" />
<p>我是父亲的:{{ info }}</p>
<button @click="handleClick">我是父亲的按钮</button>
</div>
</template>
<script>
import Son from "@/components/son";
import { ref } from "@vue/reactivity";
export default {
components: { Son },
setup() {
const info = ref('zs');
const handleClick = () => {
info = "ls";
};
return { info, handleClick };
},
};
</script>
子组件
<template>
<div>
<!-- 子组件内使用 modelValue -->
<p>我是son的:{{ modelValue }}</p>
<button @click="handleFn">我是son的按钮</button>
</div>
</template>
<script>
export default {
// 子组件接收 modelValue
props: {
modelValue: {
type: String,
},
},
setup(props, { emit }) {
const handleFn = () => {
//更新 modelValue 的值
emit('update:modelValue','ls')
};
return { handleFn };
},
};
</script>