[英]How Can I change the value of a property in a component by a Vuex store action?
我有一个Login
视图,其中包含一个登录表单和一个 function ,它调度一个名为login
的 Vuex 存储操作。 此操作发出一个POST
请求,我想知道是否可以将Login
视图中的error
属性更改为 Vuex 商店中调度的操作内部的内容。
例如,在这里面如果:
if (response.status === 401) {
console.log('Error logging in')
}
我想将 error 属性的值更改为 true。 那可能吗?
<template lang="html">
<div class="register">
<div class="register-container">
<p>Welcome back!</p>
<form @submit.prevent="onSubmit" novalidate>
<div class="margin-bottom-20">
<p>Email</p>
<input v-model='email' type='email'>
</div>
<div class="margin-bottom-20">
<p>Password</p>
<input v-model='password' type="password">
</div>
<div v-if='error'>Error</div>
<button type="submit" name="button">Continue</button>
</form>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
data(){
return {
email: '',
password: '',
error: false
}
},
methods: {
onSubmit(){
let userInfo = {
password: this.password,
email: this.email
}
this.$store.dispatch('login', userInfo)
}
}
}
</script>
这是在 Vuex 商店中找到的登录操作。
login({commit, dispatch}, userInfo){
axios.post('/login', userInfo)
.then(response => {
if (response.status === 401) {
console.log('Error logging in')
} else {
commit('authUser', {
token: response.data.token,
userId: response.data.userId,
username: response.data.username
})
router.replace('/')
}
}).catch((error) => console.log(error));
},
我在我的应用程序中执行此操作的方式是在 vuex 操作上返回 axios 响应 object,并让组件检查响应 object
例如:
// I'm gonna use async-await syntax since it's cleaner
async login({commit, dispatch}, userInfo){
try {
const response = await axios.post('/login', userInfo)
if (response.status == 401) {
commit('authUser', {
token: response.data.token,
userId: response.data.userId,
username: response.data.username
})
router.replace('/')
}
return response;
} catch (err) {
console.log(error)
}
},
在你的组件上:
methods: {
async onSubmit(){
let userInfo = {
password: this.password,
email: this.email
}
const response = await this.$store.dispatch('login', userInfo);
if (response.status === 401) {
this.error = true;
} else {
// This is optional since you already handling the router replace on the vuex actions
// However i would put the replace on here instead of in vuex action since vuex actions should only contain logic for component state.
this.$router.replace('/');
}
}
}
在 state 中添加一个名为error
的属性,并在 axios 请求回调中更新:
login({commit, dispatch}, userInfo){
axios.post('/login', userInfo)
.then(response => {
if (response.status === 401) {
console.log('Error logging in');
commit('setError',true);
} else {
commit('authUser', {
token: response.data.token,
userId: response.data.userId,
username: response.data.username
})
commit('setError',false);
router.replace('/')
}
}).catch((error) => commit('setError',true));
},
并将组件中的error
属性作为计算属性:
data(){
return {
email: '',
password: '',
}
},
computed:{
error(){
return this.$store.state.error;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.