Vue路由静态参数

Vue router static param

我想在vue router中通过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'})会得到urlhttp://localhost/center/SHOPID/productswhere SHOPID永远是static.

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

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 重新路由

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