Vue.js 路由器静态参数

Vue.js 路由器静态参数,vue.js,vuejs2,vue-router,Vue.js,Vuejs2,Vue Router,我想通过vue路由器中的url传递一些信息,例如 http://localhost/center/SHOPID/products http://localhost/center/SHOPID/categories http://localhost/center/SHOPID/... SHOPID在SPA实例的整个生命周期内不会改变,但不同的SPA实例可能会有不同的SHOPID,因为我不能将SHOPID存储在localStorage中,以避免SPA实例相互影响。如何在代码中使SHOPID透明。

我想通过vue路由器中的url传递一些信息,例如

http://localhost/center/SHOPID/products
http://localhost/center/SHOPID/categories
http://localhost/center/SHOPID/...

SHOPID在SPA实例的整个生命周期内不会改变,但不同的SPA实例可能会有不同的SHOPID,因为我不能将SHOPID存储在localStorage中,以避免SPA实例相互影响。如何在代码中使SHOPID透明。例如
vm.$router.push({name:'center.product'})
将获得url
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重新路由。

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

您是否尝试推送路由路径而不是路由名称?@StevenSpungin如果我推送路由路径,我需要先生成路径,在这种情况下,我必须获得SHOPID并处理它。你可以简单地使用@soju。如果SHOPID不同,基本URL应该不同。我不认为有问题,你应该根据需要创建路由器实例。所以如果我需要更改路由,我需要在任何地方处理SHOPID?或者您有其他解决方案使url中的字符串保持静态,例如查询字符串吗?我用一个间接寻址更新了答案,该间接寻址使用导航卫士填充shopID。使用导航卫士是个好主意。我将尝试使用全球导航卫士来处理SHOPID的所有路线。非常感谢。我无法在每次守卫前更改参数。我发现刷新窗口时很难保持shopId。我无法在警卫第一次触发时获得shopId,除非手动解析路线。所以我使用了查询字符串。它很容易通过查询字符串模块进行解析,并且在路由更改时不会更改。