頁面控制 - daniel-qa/Vue GitHub Wiki
控制頁面的顯示:就是控制 v-if 的 index 標籤
「父層把 ref(active) 直接丟給子層」,然後子層直接改父層的值,那就完全可以走 ref 傳址 的模式!
完全符合 Vue 3 Composition API 的精神:「共享狀態,直接改,不繞彎」
- 子組件
<template>
<div>
<p>批量挑選中... 現在 active = {{ active.value }}</p>
<el-button type="success" @click="goNext">進下一步</el-button>
</div>
</template>
<script setup>
import { ref } from 'vue';
const props = defineProps({
active: Object, // 傳進來是 Ref 物件
});
const goNext = () => {
props.active.value = 2; // 直接改父層的 ref
};
</script>
- 父組件
<!-- 步驟內容 -->
<div v-if="active.value === 1">
<NewMsgBatchSelect :active="active" />
</div>
<div v-if="active.value === 2">
<p>這是個別挑選步驟</p>
</div>
// 監聽 active,動態改標題
watch(active, (newVal) => {
if (newVal === 1) {
title.value = '批量挑選';
} else if (newVal === 2) {
title.value = '個別挑選';
}
});
<el-row style="height: 10vh; display: flex; justify-content: center; align-items: center;">
<!-- 上一步按钮,触发父组件事件,将 active 设置为 0 -->
<el-button type="primary" @click="goPreviousStep">上一步</el-button>
<el-button type="primary" @click="goNextStep">下一步</el-button>
</el-row>
// 上一步的逻辑:将 active 设置为 0
const goPreviousStep = () => {
emit('update-active', 0); // 通知父组件更新 active 的值为 0
};
<div v-if="active === 1">
<New_Msg_BatchSelect active="active" @update-active="updateActive" />
</div>
// 更新 active 的方法
const updateActive = (newActive) => {
active.value = newActive;
if (active.value === 1) {
title.value = "批量挑選";
}
if (active.value === 2) {
title.value = "個別挑選";
}
};