如何将数据传递到vuex动作中去

问题描述 投票:-1回答:1

我对vuex中的action不是很熟悉。

我想在我的Login组件中调用一个用axios调用api的vuex动作。

但是我的组件中传输的数据并没有在动作中被接收。

我不知道如何使这个工作... ...


this.$store.dispatch('REGISTER', {
          username: this.username,
          email: this.email,
          password: this.password
        })
        .then((response) => {
          console.log(response)
          this.$router.push('/login')
        })
        .catch (() => {
          this.error = true;
        })

在我的vuex模块中:


import axios from "axios";

export default {
  state: {},
  mutations: {},
  getters: {},
  actions: {
    REGISTER: ({ username, email, password }) => {
      return new Promise((resolve, reject) => {
        axios
          .post(process.env.VUE_APP_API_URL + "auth/register", {
            username: username,
            email: email,
            password: password
          })
          .then(({ data, status }) => {
            if (status === 201) {
              localStorage.setItem('access_token', data.data.token);
              resolve(true);
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    },
  }
};

谢谢

javascript vue.js vuex vuex-modules
1个回答
1
投票

你正在向vuex动作传递一个对象。试着修改你的动作方法。

REGISTER: ({ commit }, data) => {
let {username, email, password} = data

EDIT: 具体来说,任何vuex动作接收到的第一个参数都是一个上下文对象,包含提交,状态,获取者和派遣。第二个参数是你通过调用dispatch传递给它的任何对象。– maiorano84

© www.soinside.com 2019 - 2024. All rights reserved.