现在有两个路由,它们共用一个组件,如何实现组件的复用?
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实现的页面:
实现方法
在页面中的
给
在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;
},
},