vue公共布局组件Layout引入

需求,后台系统有一个公共的头部:

 

 

这个在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>

  知乎账号:空格之王

posted @ 2021-06-26 11:52  小虫1  阅读(4799)  评论(0编辑  收藏  举报