在导航路线时保留参数

问题描述 投票:0回答:2

如何在导航路线时保留参数。参数必须位于应用程序的每个页面中(不仅仅是嵌套路由中)。在 Angular 中,我可以使用

this._router.navigate([''], { queryParamsHandling: 'merge' })
做到这一点,但是如何使用 vue.js 做到这一点?

基本路线示例:

// base route 1 -> http://example.test/?user_code=1234&member=false
// base route 2 -> http://example.test/?user_code=56789&member=false
// base route 3 -> http://example.test/?user_code=4321

如何在我导航的每条路线中保留参数

user_code
member

我想要的例子

// navigated route 1 -> http://example.test/about?user_code=1234&member=false
// navigated route 2 -> http://example.test/whatever_page?user_code=56789&member=false
// ...

为什么我需要这个?因为那样我将需要参数来在应用程序中执行操作

Ex: this.$route.query.user_code == '1234' ? 'do this' : 'do that';

提前谢谢您!

javascript vue.js vue-router
2个回答
3
投票

一种典型的方法是使用状态并将路由的 fullPath 推送到该状态属性(可能是一个数组)中。

使用 vuex:

// store/index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    paths: []
  },
  mutations: {
    PUSH_PATH (fullPath) {
      paths.push(fullPath)
    }
  },
  actions: {
    pushPath(commit, fullPath) {
       commit("PUSH_PATH", fullPath)  
    }
  } 
})
// in a component
import { mapActions } from "vuex";
...

  methods: {
    ...mapActions("pushPath")
  },
  created() {
    this.pushPath(this.$route.fullPath)
  }

现在,如果您使用pushPath,当创建视图时,它会将 fullPath 添加到数组中,您稍后可以通过注入、检查等方式做出决定。

另一个流行的选择,特别是在根据路线做出决策时,是使用“导航守卫”。这些函数可以拦截路由并允许您执行某些操作。更多详细信息请访问:https://router.vuejs.org/guide/advanced/navigation-guards.html


0
投票

这里有几个使用导航防护来保存查询参数的示例。要使用此技术保留单个

foo
参数:

router.beforeEach((to, from) => {
  if ('foo' in from.query && !('foo' in to.query)) {
    return { ...to, query: { ...to.query, foo: from.query.foo } };
  }
  return true;
});

复制

from
中但不在
to
中的所有内容:

router.beforeEach((to, from) => {
  const missing = Object.entries(from.query).filter(([k]) => !(k in to.query));
  if (missing.length > 0) {
    return { ...to, query: { ...to.query, ...Object.fromEntries(missing) } };
  }
  return true;
});
© www.soinside.com 2019 - 2024. All rights reserved.