多路由复用一个组件

现在有两个路由,它们共用一个组件,如何实现组件的复用?

route代码:

export const catalogRouter: MenuConfig = {
    path: "/catalog",
    component: Catalog,
    title: "目录管理",
    key: "catalog",
    name: "catalog",
    children: [
    {
        path: "catalogCreate",
        title: "目录添加",
        hasPermission: true,
        name: "CatalogCreate",
        key: "CatalogCreate",
        component: CatalogDetail,
    },
    {
        path: "catalogEdit",
        title: "目录编辑",
        hasPermission: true,
        name: "CatalogEdit",
        key: "CatalogEdit",
        component: CatalogDetail,
    }],
};

两个路由分别是 CatalogCreate 和 CatalogEdit,它们共用了一个组件 CatalogDetail。CatalogCreate实现的功能是目录的添加,CatalogEdit则是对目录信息的编辑,因为它们页面上的区别仅仅是显示数据的区别,所以可以共用一个组件。

CatalogCreate实现的页面:

《多路由复用一个组件》

CatalogEdit实现的页面:

《多路由复用一个组件》

实现方法

在页面中的 <router-view> 标签上绑定一个key属性,用来给它增加一个随机数,以此让每次进入<router-view>的路由名都不相同,这就让vue认为每次渲染的都是新组件,从而达到刷新的目的。

给<router-view> 绑定一个key属性

<router-view :key="key"></router-view>

在ts中,就需要对这个 key 实现随机数功能

computed: {
    key() {
        return this.$route.name !== undefined ? this.$route.name + new Date().getTime().toString() : this.$route + new Date().getTime().toString();
    },
},

key() 中返回的是三元表达式,在路由名不为 undefined 的时候,路由名等于它自己的后面加上个时间戳,new Date().getTime() 返回一个很长的随机数,这样拼接到一起就实现了路由名的随机。

既然是为了得到一个随机数,上面这个方法可以,但并不是我们常规做随机数的方法,所以也可以使用常规的random。

computed: {
    key() {
        const randomNumber = Math.random().toString();
        return this.$route.name !== undefined ? this.$route.name + randomNumber : this.$route + randomNumber;
    },
},

    原文作者:bertZuo
    原文地址: https://segmentfault.com/a/1190000019195782
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞