面包屑是我们在项目中经常使用的一个功能,一般情况下它用来表示我们当前所处的站点位置,也可以快速回到上个层级。

   安装相关依赖

npm i element-ui -S

安装element-ui

npm install vue-router

安装vue-router

main.js中引入

​
import Vue from 'vue'
import VueRouter from 'vue-router'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(VueRouter)
Vue.use(ElementUI);
​

在route文件夹下的index.js文件中做配置

import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";

Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    name: "Home",
    component: Home,
    meta: { title: "首页", path: "/" }, //meta属性,可在页面中用this.$route这里的两个属性
    //重定向 访问到/的都会重定向到/edit  命名自定义
    redirect: "/edit",
    children: [
      //子组件
      {
        path: "/edit",
        name: "Edit",
        component: () => import("../views/edit.vue"),
        meta: { title: "编辑", path: "/edit" },
      },
      {
        path: "/del",
        name: "Del",
        component: () => import("../views/del.vue"),
        meta: { title: "删除", path: "/del" },
      },
    ],
  },
  {
    path: "/about",
    name: "About",
    component: () => import("../views/About.vue"),
    meta: { title: "关于", path: "/" },
  },
];

const router = new VueRouter({
  routes,
});

export default router;

在src文件夹下的components文件夹新建一个Bread.vue文件

​
<template>
  <div>
    <el-breadcrumb separator="/">
      <!-- to为点击跳转 title为路由中的meta属性定义的标题 -->
      <el-breadcrumb-item
        v-for="(v, i) in breadList"
        :key="i"
        :to="v.meta.path"
        >{{ v.meta.title }}</el-breadcrumb-item
      >
    </el-breadcrumb>
  </div>
</template>

<script>
export default {
  data() {
    return {
      breadList: [],
    };
  },
  watch: {
    $route() {//监听$route
      this.getBreadcrumb();
    },
  },
  methods: {
    isHome(route) {
      return route.name === "home";
    },
    getBreadcrumb() {
      let matched = this.$route.matched;
      //如果不是首页
      if (!this.isHome(matched[0])) {
        matched = [].concat(matched);
      }
      this.breadList = matched;
    },
  },
  created() {
    //生命周期中调用获取数据的方法
    this.getBreadcrumb();
  },
};
</script>
<style lang="" scoped></style>

​

在Home.vue中引入

<template>
  <div class="home">
    <!-- 使用组件 -->
    <Bread />
  </div>
</template>

<script>
// @ is an alias to /src
import Bread from "../components/Bread.vue";//引入组件
export default {
  name: "Home",
  components: { Bread },//注册组件
 
  methods: {
    
  },
};
</script>

此时页面如下

因为用了重定向所以指向编辑,也就是/edit

当我们去向/del页面时,效果如下

这样,一个动态的面包屑就完成了

Logo

前往低代码交流专区

更多推荐