Vue router 静态参数



我想通过 vue 路由器中的 url 传递一些信息,例如 http://localhost/center/SHOPID/products http://localhost/center/SHOPID/categories http://localhost/center/SHOPID/... SHOPID 在整个 SPA 实例生命周期中不会更改,但不同的 SPA 实例可能具有不同的 SHOPID,因为我无法将 SHOPID 存储在本地存储中,以避免 SPA 实例相互影响。如何使 SHOPID 在我的代码中透明。例如vm.$router.push({name:'center.product'})将获得网址http://localhost/center/SHOPID/products其中 SHOPID 始终是静态的。

您可以像这样添加路径参数:

router.push({ name: 'center.product', params: { SHOPID: theShopId }})

或者,您可以使用字符串替换文本推送路径。

router.push({ path: `center/${theShopId}/products` })

这假设您使用参数定义了路径。

center/:SHOPID/products

您还可以设置导航防护装置,并重定向到其他路线,从会话中添加您的 SHOPID

routes: [
{
path: 'center/products',
component: Products,
beforeEnter: (to, from, next) => {
next({ name: 'center.product', params: { SHOPID: $store.state.shopId }})
}

或使用查询而不是路径参数

routes: [
{
path: 'center/products',
component: Products,
beforeEnter: (to, from, next) => {
next({ name: 'center.product', query: { shopId: $store.state.shopId }})
}

当您推送center/products时,它将使用来自您的商店、上下文、会话、数据库等的商店 ID 重新路由。

您可以为此使用meta字段。 https://router.vuejs.org/guide/advanced/meta.html

文档中的示例:

routes = [
{
path: 'sample',
meta: { shopId: 'id' }
}
];

最后,我使用查询字符串来解决我的问题。使用网址http://localhost/?shopId=123#/products.我在应用程序启动时解析了查询字符串,并将shopId存储在全局对象中以访问后者。当哈希字符串更改时,查询字符串将是静态的。

最新更新