一、定义三个子组件
FormOne.vue、FormTwo.vue分别调用FormHelper,并在FormHelper中使用slot插槽占位
FormHelper.vue如下
<template>
<div>
<h1>填充以下表单内容</h1>
<form>
<div id="form-header">
<slot name="form-header"></slot>
</div>
<div id="form-fields">
<slot name="form-fields"></slot>
</div>
<div id="form-controls">
<slot name="form-controls"></slot>
</div>
</form>
</div>
</template>
<script>
export default {
data() {
return {};
}
};
</script>
<style scoped>
</style>
FormOne.vue如下:
<template>
<div>
<form-helper>
<div slot="form-header">
<h3>这里是FormOne</h3>
</div>
<div slot="form-fields">
<h3>这里是FormOne</h3>
</div>
<div slot="form-controls">
<h3>这里是FormOne</h3>
</div>
</form-helper>
</div>
</template>
<script>
import formHelper from "./FormHelper.vue";
export default {
data() {
return {};
},
components: {
"form-helper": formHelper
}
};
</script>
<style scoped>
div {
background: lightcyan;
}
</style>
FormTwo.vue如下:
<template>
<div>
<form-helper>
<div slot="form-header">
<h3>这里是FormTwo</h3>
</div>
<div slot="form-fields">
<h3>这里是FormTwo</h3>
</div>
<div slot="form-controls">
<h3>这里是FormTwo</h3>
</div>
</form-helper>
</div>
</template>
<script>
import formHelper from "./FormHelper.vue";
export default {
data() {
return {};
},
components: {
"form-helper": formHelper
}
};
</script>
<style scoped>
div {
background: lightsalmon;
}
</style>
二、在App.vue中注册FormOne.vue、FormTwo.vue
import FormOne from "./components/FormOne";
import FormTwo from "./components/FormTwo";
export default {
name: "App",
components: {
"form-one": FormOne,
"form-two": FormTwo
},
data() {
return {
whichcomponent: "form-one"
};
},
methods: {}
};
</script>
三、使用component标签动态切换组件
<template>
<div id="app">
<component :is="whichcomponent"></component>
<button @click="whichcomponent='form-one'">显示formOne</button>
<button @click="whichcomponent='form-two'">显示formTwo</button>
</div>
</template>
四、浏览器端访问并测试
点击“显示formTwo”按钮
点击“显示formOne”按钮