所有的 props 都遵循着单向绑定原则,props 因父组件的更新而变化,自然地将新的状态向下流往子组件,而不会逆向传递。这避免了子组件意外修改父组件的状态的情况,不然应用的数据流将很容易变得混乱而难以理解。
- 使用 emits 自定义事件以参数方式在父组件更新;
- 使用 emits 自定义 v-model 实现双向绑定更新(推荐);
- 提高作用域,使用 Pinia 实现更新(不推荐)。
使用自定义双向绑定实现子组件改变父组件状态。
1️⃣子组件:
const props = defineProps({
disabled: {
type: Boolean,
required: true
}
});
const bol = ref(props.disabled);
const emits = defineEmits(["update:disabled"]);
function handleClick() {
emits("update:disabled", (bol.value = !bol.value));
}
定义 emitOption,事件名称必须是 update:xxx
格式,xxx 必须对应 prop 名称。数据发生改变的位置处,调用 emits('update:xxx', value)
函数进行更新。
<template>
<button @click="handleClick">Click Me</button>
</template>
2️⃣父组件:
const state = ref(false);
<template>
{{ state }}
<Test v-model:disabled="state" />
</template>
父组件中,在子组件上使用指令 v-model:xxx
,可以收到 emit 发送过来的状态消息,对父组件 state 进行更新。
实现效果: