简介
在Vue中,component是一个内置组件,也叫做动态组件,可以作为一个占位符使用,主要用于展示不同的组件。通常在tab页切换,多操作页面等中使用。
<component :is="currentRole" ref="componentscjk" :form="form" @refreshListTree="refreshListTree" />
通过v-bind:is动态绑定组件名称,如上述代码中的currentRole要与所渲染的组件的名称相同
该可以给子组件传递值、方法,如上述代码中将值form与方法refreshListTree传递给子组件
component的使用通常结合了transition与keep-alive
例子
以下是一个分步表单,每一个步骤对于一个组件:
目录结构:
index.vue
<template>
<div class="step-form">
<section class="form-box">
<a-steps :current="current">
<a-step description="确保填写正确">填写转账信息</a-step>
<a-step description="确认转账信息">确认转账信息</a-step>
<a-step description="恭喜您,转账成功">完成转账</a-step>
</a-steps>
<transition name="fade-slide" mode="out-in" appear>
<keep-alive>
<component :is="stepMap[current]" :form="form" @next="next" @prev="prev" @again="current = 1"></component>
</keep-alive>
</transition>
</section>
</div>
</template>
<script setup lang="ts" name="StepForm">
import Step1 from './Step1.vue'
import Step2 from './Step2.vue'
import Step3 from './Step3.vue'
import type { StepForm } from './type'
const stepMap: any = {
1: Step1,
2: Step2,
3: Step3,
}
const current = ref(1)
const form = ref<StepForm>({
payAccount: '',
recAccount: '',
payType: 1,
recName: '',
amount: '0',
})
const next = (formData: StepForm) => {
current.value++
if (formData) {
form.value = formData
}
}
const prev = () => {
current.value--
}
</script>
<style lang="scss" scoped>
.step-form {
flex: 1;
margin: $margin;
padding: $padding;
background: var(--color-bg-1);
display: flex;
justify-content: center;
box-sizing: border-box;
.form-box {
width: 50%;
min-width: 500px;
margin-top: 30px;
flex-shrink: 0;
}
}
</style>