0

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

这是有效的:

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”的上下文没有到达路由器或其中的推送功能。如何访问路由器并路由到下一页?

4

1 回答 1

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(() => { })
    }
  }
}
于 2020-02-10T06:36:15.187 回答