子给父组件传递数据,KeepAlive缓存
component切换组件
1.父组件
<script setup>
import coma from './components/coma.vue'
import comb from './components/comb.vue'
import comc from './components/comc.vue'
import comd from './components/comd.vue'
import { shallowRef, ref } from 'vue'
// 变化的序号
const active = ref('0')
// 响应式组件
const names = shallowRef(coma)
const arr = [coma, comb, comc, comd]
const fun = (item) => {
names.value = arr[item]
console.log(names.value)
// 从子组件传过来的数据
console.log(item)
active.value = item
}
</script>
<template>
<div>
<p>
<span v-for="(item, index) in 4" :style="{ 'color': index == active ? '#60a7a7' : '#787878' }">第{{ item }}步</span>
</p>
<!-- 缓存 -->
<KeepAlive>
<component :is="names" @add="fun"></component>
</KeepAlive>
</div>
</template>
<style scoped>
span {
padding: 0px 10px;
border-bottom: 1px solid #4ea5c3;
}
;
</style>
2.子组件
(1)
<template>
<div class="box">
输入姓名: <input type="text">
<button @click="$emit('add', '1')">下一步</button>
</div>
</template>
<script setup>
const emit = defineEmits(['add'])
</script>
<style scoped="scoped">
.box {
display: block;
border: 2px solid rgb(255, 155, 155);
width: 244px;
color: rgb(255, 174, 174);
}
button:focus {
outline: 0;
}
button:hover {
color: rgb(255, 255, 255);
background-color: rgb(255, 169, 169);
border: none;
}
input {
outline: none;
border: 1px rgb(105, 208, 228) solid;
}
</style>
(2)
<template>
<div class="box">
输入密码: <input type="text">
<button @click="$emit('add', '2')">下一步</button>
</div>
</template>
<script setup>
const emit = defineEmits(['add'])
</script>
<style scoped="scoped">
.box {
display: block;
border: 2px solid rgb(99, 124, 234);
width: 244px;
color: rgb(174, 201, 255);
}
button:focus {
outline: 0;
}
button:hover {
color: rgb(255, 255, 255);
background-color: rgb(127, 118, 255);
border: none;
}
input {
outline: none;
border: 1px rgb(105, 208, 228) solid;
}
</style>
(3)
<template>
<div class="box">
重复密码: <input type="text">
<button @click="$emit('add', '1')">上一步</button>
<button @click="$emit('add', '3')">下一步</button>
</div>
</template>
<script setup>
const emit = defineEmits(['add'])
</script>
<style scoped="scoped">
.box {
display: block;
border: 2px solid rgb(155, 255, 201);
width: 244px;
color: rgb(47, 136, 84);
}
button:focus {
outline: 0;
}
button:hover {
color: rgb(255, 255, 255);
background-color: rgb(141, 243, 209);
border: none;
}
input {
outline: none;
border: 1px rgb(105, 208, 228) solid;
}
</style>
(4)
<template>
<div class="box">
<button @click="$emit('add', '2')">上一步</button>
<button>完成</button>
</div>
</template>
<script setup>
const emit = defineEmits(['add'])
</script>
<style scoped="scoped">
.box {
display: block;
border: 2px solid rgb(255, 229, 156);
width: 244px;
color: rgb(255, 179, 80);
}
button:focus {
outline: 0;
}
button:hover {
color: rgb(255, 255, 255);
background-color: rgb(255, 195, 44);
border: none;
}
</style>