首页 > 解决方案 > 使用 Vuex 将数据从 FormulateForm 传递到映射操作

问题描述

我目前正在使用 Vue Formulate 将数据传递@submit="login"FormulateForm一个login(data)函数。只要我将逻辑保留在组件内,并且可以data使用 axios 将其发送到我的服务器,一切都运行良好。

事情是,我想把这个登录函数作为一个动作放在我的 Vuex 存储中,但是当我将@submit="login"from引用FormulateForm...mapActions(["login"])函数时,里面没有传递数据。我登录data了这个login(data)动作,我得到了这个:

来自 vuex 模块中 console.log(data) 的响应

我可以将输入中的值绑定到商店并从那里获取它们,但我更愿意保持简单并使用@submit.

有可能这样做吗?

正在运行的实际代码概述:

methods: {
  login(data) {
    axios
      .post("http://localhost:3000/api/auth/login", data, {
        withCredentials: true
      })
      .then(res => {
        if (res.status === 200) {
          this.setUserRole(res.data.isAdmin);
          this.$router.push("/");
        }
      })
      .catch(err => {
        if (err.response.status === 404) {
          // TODO: gestion d'erreur
        } else if (err.response.status === 401) {
          // TODO: gestion d'erreur
        }
      });
  }
)
<FormulateForm @submit="login">

我想要的概述,这是行不通的:

methods: {
  ...mapActions(["login"])
)
<FormulateForm @submit="login">

在 Vuex 模块 user.js 中:

const actions = {
  login: data => {
    console.log(data);
    axios
      .post("http://localhost:3000/api/auth/login", data, { withCredentials: true })
      .then(res => {
        if (res.status === 200) {
          this.setUserRole(res.data.isAdmin);
          this.$router.push("/");
        }
      })
      .catch(err => {
        if (err.response.status === 404) {
          // TODO: gestion d'erreur
        } else if (err.response.status === 401) {
          // TODO: gestion d'erreur
        }
      });
  }
};

如前所述,它不会像当前console.log(data)那样返回我的FormulateForm值。

标签: vue.jsvuexvue-formulate

解决方案


您没有分派 action login

做这个

<FormulateForm @submit="handleLogin">

methods: {
  ...mapActions(["login"]), // here, you have mapped `this.login()` to this.$store.dispatch('login')
  handleLogin(data) {
    this.login(data);  // pass data as a parameter
  }
)

然后您的 vuex user.js 存储应更改为

const actions = {
  login: ({commit, state}, data) => { // it takes two arguments here
    console.log(data);
  }
};

有关操作的更多信息,请查看 Vuex文档

做这些事情,它应该工作。


推荐阅读