如何从 Vuex 状态使用 Vue Router?

编程入门 行业动态 更新时间:2024-10-11 03:16:03
本文介绍了如何从 Vuex 状态使用 Vue Router?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

在我一直使用的组件中:

In my components I've been using:

this.$router.push({ name: 'home', params: { id: this.searchText }});

改变路线.我现在已经将一个方法移动到我的 Vuex 动作中,当然 this.$router 不再起作用.Vue.router 也没有.那么,请问如何从 Vuex 状态调用路由器方法?

To change route. I've now moved a method into my Vuex actions, and of course this.$router no longer works. Nor does Vue.router. So, how do I call router methods from the Vuex state, please?

推荐答案

我假设 vuex-路由器同步在这里没有帮助,因为您需要路由器实例.

I'm assuming vuex-router-sync won't help here as you need the router instance.

因此,虽然这感觉并不理想,但您可以将实例设置为 webpack 中的全局实例,即

Therefore although this doesn't feel ideal you could set the instance as a global within webpack, i.e.

global.router = new VueRouter({
  routes
})

const app = new Vue({
  router
  ...

现在您应该能够:router.push({ name: 'home', params: { id: 1234 }}) 从您应用内的任何位置

now you should be able to: router.push({ name: 'home', params: { id: 1234 }}) from anywhere within your app

作为替代,如果您不喜欢上述想法,您可以从您的操作中返回一个 Promise.然后,如果操作成功完成,我假设它调用了突变或其他东西,您可以resolve Promise.但是,如果它失败并且重定向所需的任何条件都会命中您reject Promise.

As an alternative if you don't like the idea of the above you could return a Promise from your action. Then if the action completes successfully I assume it calls a mutation or something and you can resolve the Promise. However if it fails and whatever condition the redirect needs is hit you reject the Promise.

通过这种方式,您可以将路由器重定向移动到一个组件中,该组件简单地捕获被拒绝的 Promise 并触发 vue-router 推送,即

This way you can move the routers redirect into a component that simply catches the rejected Promise and fires the vue-router push, i.e.

# vuex
actions: {
  foo: ({ commit }, payload) =>
    new Promise((resolve, reject) => {
      if (payload.title) {
        commit('updateTitle', payload.title)
        resolve()
      } else {
        reject()
      }
    })

# component
methods: {
  updateFoo () {
    this.$store.dispatch('foo', {})
      .then(response => { // success })
      .catch(response => {
        // fail
        this.$router.push({ name: 'home', params: { id: 1234 }})
      })

这篇关于如何从 Vuex 状态使用 Vue Router?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-27 01:10:41,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1145679.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:状态   Vuex   Router   Vue

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!