vue.js - 使用 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
值。
解决方案
您没有分派 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文档
做这些事情,它应该工作。
推荐阅读
- php - 我想在 php 中创建 if else 但我不知道如何
- shell - 在 vim 的 shell 中编辑命令行
- mongodb - 如何在猫鼬中获取子文档群体的特定字段
- reactjs - ReactJS 中的 ScrollToRef - 隐式类型
- matlab - MATLAB如何组合两个不同长度的数组
- python - 是否可以获取我在 Facebook Messenger 上发送的所有消息?
- deep-learning - 使用预训练的 VGG-16 从图像中获取特征向量
- python - 如何使用pickle.load()读取完整文件?
- php - Array to string conversion for calculate discount (not resolved in similar question)
- scala - 是 scala REPL 打印的实例名称/ID 吗?