目录:
一、动态组件
比如我们现在想要实现了一个功能:
- 点击一个tab-bar,切换不同的组件显示;
这个案例我们可以通过两种不同的实现思路来实现:
- 方式一:通过v-if来判断,显示不同的组件;
- 方式二:动态组件的方式;
1.1. v-if显示不同组件
我们可以先通过v-if来判断显示不同的组件,这个可以使用我们之前讲过的知识来实现:
<template>
<div>
<button v-for="tab in tabs"
:key="tab"
:class="{active: currentTab === tab}"
@click="tabClick(tab)">
{
{tab}}
</button>
<template v-if="currentTab === 'home'">
<home></home>
</template>
<template v-else-if="currentTab === 'about'">
<about></about>
</template>
<template v-else>
<category></category>
</template>
</div>
</template>
<script>
import Home from "./pages/Home.vue";
import About from "./pages/About.vue";
import Category from "./pages/Category.vue";
export default {
components: {
Home, About, Category
},
data() {
return {
tabs: ["home", "about", "category"],
currentTab: "home"
}
},
methods: {
tabClick(tab) {
this.currentTab = tab;
}
}
}
</script>
<style scoped>
.active {
color: red;
}
</style>
1.2. 动态组件的实现
动态组件是使用 component 组件,通过一个特殊的attribute is 来实现:
<template>
<div>
<button v-for="tab in tabs"
:key="tab"
:class="{active: currentTab === tab}"
@click="tabClick(tab)">
{
{tab}}
</button>
<component :is="currentTab"></component>
</div>
</template>
这个currentTab的值需要是什么内容呢?
- 可以是通过component函数注册的组件;
- 在一个组件对象的components对象中注册的组件;
1.3. 动态组件的传值
如果是动态组件我们可以给它们传值和监听事件吗?
- 也是一样的;
- 只是我们需要将属性和监听事件放到component上来使用;
App.vue的代码如下:
<template>
<div>
<button v-for="tab in tabs"
:key="tab"
:class="{active: currentTab === tab}"
@click="tabClick(tab)">
{
{tab}}
</button>
<component name="why"
:age="18"
@pageClick="pageClick"
:is="currentTab"/>
</div>
</template>
<script>
import Home from "./pages/Home.vue";
import About from "./pages/About.vue";
import Category from "./pages/Category.vue";
export default {
components: {
Home, About, Category
},
data() {
return {
tabs: ["home", "about", "category"],
currentTab: "home"
}
},
methods: {
tabClick(tab) {
this.currentTab = tab;
},
pageClick(payload) {
console.log("pageClick", payload);
}
}
}
</script>
<style scoped>
.active {
color: red;
}
</style>
Home.vue中的代码如下:
<template>
<div @click="pageClick">
Home组件: {
{name}}-{
{age}}
</div>
</template>
<script>
export default {
props: {
name: String,
age: Number
},
emits: ["pageClick"],
methods: {
pageClick() {
this.$emit("pageClick", "Home组件");
}
}
}
</script>
1.4. keep-alive使用
1.4.1. 认识keep-alive
我们先对之前的案例中About组件进行改造:
- 在其中增加了