vue 动态添加路由

144 阅读1分钟

根据接口返回的菜单栏数据,动态配置路由,因为菜单栏有二级目录,所以数组循环方法需要嵌套使用。

  methods: {
    getNavList() {
      axios.get("/mock/menu.json").then((res) => {
        let { data, meta } = res.data;
        if (meta.status == 200) {
          this.navList = data;
          let arr = this.navList.slice(1, 4);
          arr.forEach((v) => {
            v.children.forEach((r) => {
              this.$router.addRoute("index", {
                path: r.path,
                name: r.path,
                component: () =>
                  import(
                    `@/views/${
                      r.path.substring(0, 1).toUpperCase() + r.path.substring(1)
                    }View.vue`
                  ),
              });
            });
          });
        } else {
          this.$message.error(meta.msg);
        }
      });
    },
  },

⭐⭐⭐⭐