如何在 Vuex 操作中使用 Vue 路由器进行导航

新手上路,请多包涵

我正在使用 Vue 2.x 和 Vuex 2.x 创建一个 Web 应用程序。我正在通过 http 调用从远程位置获取一些信息,我希望如果该调用失败,我应该重定向到其他页面。

 GET_PETS: (state) => {
  return $http.get('pets/').then((response)=>{
      state.commit('SET_PETS', response.data)
    })
  },
  error => {this.$router.push({path:"/"}) }
  )
}

但是 this.$router.push({path:"/"}) 给了我以下错误。

Uncaught (in promise) TypeError: Cannot read property ‘push’ of undefined

这怎么可能实现。

模拟 JsFiddle: 这里

原文由 Saurabh 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 277
2 个回答

import router from './router'

并使用 router.push

就这么简单。

原文由 Marek Urbanowicz 发布,翻译遵循 CC BY-SA 4.0 许可协议

这个例子可以帮助你。

main.js

 import Vue from "vue";
import VueRouter from "vue-router";

...

Vue.use(VueRouter);

export const router = new VueRouter({
    mode: 'hash',
    base: "./",
    routes: [
        { path: "/", component: welcome},
        { path: "/welcome", component: welcome},

    ]
})

动作.js

 import {router} from "../main.js"

export const someAction = ({commit}) => {

    router.push("/welcome");
}

原文由 bocai 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题