【问题标题】:$router.push() not a function error using Vuex$router.push() 不是使用 Vuex 的函数错误
【发布时间】:2020-05-25 10:51:33
【问题描述】:

创建新项目后,我想将用户引导到另一个页面,以便他们可以向项目添加更多信息。

这是有效的:

createProject() {
      ProjectService.createProject(this.project)
        .then(response => {
          this.$router.push({
            name: "project-update",
            params: { id: response.data.data.id }
          });
        })
}

我想使用 vuex 来处理这一切,但这不起作用。

createProject() {
  this.$store
    .dispatch("project/postProject", this.project)
    .then(response => {
      this.$router.push({
        name: "project-update",
        params: { id: response.data.data.id }
      });
    })
    .catch(() => {});
}

我得到的错误是:"state.projects.push is not a function"

这是我在 Vuex 中的 postProject 操作:

  postProject({ commit, dispatch }, project) {
    return ProjectService.createProject(project)
      .then(() => {
        commit('ADD_PROJECT', project);
        const notification = {
          type: 'success',
          message: 'Your project has been created!'
        };
        dispatch('notification/add', notification, { root: true });
      })
      .catch(error => {
        const notification = {
          type: 'error',
          message: 'There was a problem creating your project: ' + error.message
        };
        dispatch('notification/add', notification, { root: true });
        throw error;
      });
  }

看起来“this”的上下文没有到达路由器或其中的推送功能。如何访问路由器并路由到下一页?

【问题讨论】:

  • 你能添加你的调度动作和变异代码吗?
  • action和dispatch工作正常,数据成功存入数据库和state,只有router不工作。
  • 您需要将路由器模块包含到该 vuex 模块中并使用router.push()
  • 那你怎么得到这个错误 state.projects.push is not a function?只需尝试评论 router.push 行并检查它是否仍然抛出此错误。
  • @KarmaBlackshaw 如何添加路由器模块?我应该简单地将我在这里拥有的东西放入动作中,还是必须包括一些东西?

标签: javascript vue.js vuejs2 vuex vue-router


【解决方案1】:

你可以像这样将你的路由模块导入你的 vuex 模块:

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

export default {
  actions: {
    createProject () {
      this.$store
        .dispatch("project/postProject", this.project)
        .then(response => {
          router.push({
            name: "project-update",
            params: { id: response.data.data.id }
          })
        })
        .catch(() => { })
    }
  }
}

【讨论】:

  • 你能展示你的新 createProject 方法吗?如果您仍然使用this.$router,请将其更改为仅router
  • 我注意到这一点后删除了我的最新评论。更改了我的代码以反映您的代码,但我仍然收到“state.projects.push is not a function”错误
  • 尝试了两种导入方式
  • 路由器部分完成。接下来是你的postProject,它似乎有一个错误的实现。你能展示你的postProject 方法吗?
  • 很可能你的状态变量projects 是一个对象而不是一个数组。您应该首先通过执行变量 state.projects 的 typeOf 控制台来检查。
猜你喜欢
  • 1970-01-01
  • 2021-04-17
  • 2020-05-23
  • 2022-01-16
  • 2020-10-07
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
  • 2018-12-09
相关资源
最近更新 更多