需求,后台系統有一個公共的頭部:

這個在3個頁面中寫3份頭部,肯定是不優雅的。vue提供的組件思想,我們可以將這個公共的頭部組件化:src/components/HeaderComponent.vue
<template>
<header>
<img src="../assets/images/logo.png" alt="" />
<h1>智星雲</h1>
<ul v-if="showNav">
<li
v-for="(nav, index) in navArr"
:key="index"
:class="index === activeIndex ? 'active' : ''"
@click="toNav(index, nav.path)"
>
{{ nav.name }}
</li>
</ul>
</header>
</template>
<script>
export default {
data() {
return {
navArr: [
{
name: "雲市場",
path: "/store",
},
{
name: "控制台",
path: "/console",
},
{
name: "文檔",
path: "/docs",
},
],
activeIndex: 0,
};
},
created() {},
methods: {
toNav(index, path) {
this.$router.push({
path: path,
});
},
},
watch: {
$route: {
handler(newRoute) {
let path = newRoute.path;
this.activeIndex = this.navArr.findIndex((arr) => arr.path === path);
},
immediate: true,
},
},
};
</script>
現在有了這個公共的頭部組件,接下來是怎么引入的問題了。有以下3種辦法:
1.頁面中用組件的方式引入
import HeaderComponent from "../../components/HeaderComponent.vue";
export default {
components: { HeaderComponent },
}
這種做法不是不可以,只是在3個頁面都這么做,一定不優雅的。
2.嵌套路由的方式引入
{
path: '/store',
component: HeaderComponent,
children: [
{
path: '/store',
component: StoreIndex,
}
]
}
這種相對於第一種,已經比較優雅。
3.動態組件引入
// App.vue
<template>
<div id="app">
<component :is="layout">
<router-view />
</component>
</div>
</template>
<script>
import DefaultLayout from "./views/DefaultLayout.vue";
import Layout from "./views/Layout.vue";
export default {
components: {
DefaultLayout,
Layout,
},
computed: {
layout() {
return this.$route.meta.layout || DefaultLayout;
},
},
};
</script>
//路由
{ path: '/store', component: StoreIndex, meta: { title: '雲市場', layout: 'Layout' } },
//Layout.vue
<template>
<div>
<HeaderComponent />
<router-view />
</div>
</template>
<script>
import HeaderComponent from "../components/HeaderComponent.vue";
export default {
components: {
HeaderComponent,
},
};
</script>
<style lang="less">
</style>
//defaultLayout
<template>
<router-view />
</template>
<script>
export default {};
</script>
知乎賬號:空格之王。
