javascript - 在路由中导航时保留参数

标签 javascript vue.js vue-router

如何在路由中导航时保留参数。参数/参数必须在应用程序的每个页面中(不仅在嵌套路由中)。在 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

如何在我导航的每条 route 保留参数 user_codemember

我想要的例子

// 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' ? '做这个' : '做那个';

提前致谢!

最佳答案

典型的方法是使用状态并将路由的完整路径推送到该状态属性(可能是数组)。

使用 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,当您的 View 被创建时,它会将 fullPath 添加到一个数组中,您稍后可以通过注入(inject)、检查等方式做出决定。

另一种流行的选择,尤其是在根据路线做出决策时,是使用“Navigation Guards”。这些是拦截路线并允许您执行某些操作的功能。此处提供更多详细信息:https://router.vuejs.org/guide/advanced/navigation-guards.html

关于javascript - 在路由中导航时保留参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70585151/

相关文章:

javascript - 为 Web 应用程序构建 Javascript 文件

javascript - 旧版浏览器中的 Vue.js 条件渲染

laravel - 子路由仍然只加载父组件

vue.js - Vue 路由器。 Root Vue没有数据?

javascript if (a.b.v.c.d.e === true)

javascript - typescript 问题 - 澄清几点

javascript - 如何在 Chrome 打包应用程序的 list 中使用 "system_indicator"?

javascript - Vuex 渲染错误

javascript - Vue2尝试拼接对象的最后一个元素时出错

vue.js - 为什么我的 Vue Router 没有路由到我的组件?