如何在提交表单后每次更新vuex状态



基本上我使用的是Vue 3,并且我试图分配服务器返回的错误,例如,如果电子邮件已经被另一个用户接收。第一次工作正常时,我可以将服务器返回的消息分配给我的state.responseErrorMessage属性,但当我尝试在不刷新页面的情况下使用新电子邮件重新发送发件人时,ERROR_message突变不会更新!

myComponent:

<script>
computed: {
...mapState(['responseSuccessMessage','responseErrorMessage']),
},
methods: {
...
if( this.errors.firstname.errMsg === null && 
this.errors.lastname.errMsg === null && 
this.errors.email.errMsg === null && 
this.errors.password.errMsg === null && 
this.errors.passwordConfirm.errMsg === null &&
this.errors.terms.errMsg === null) {
this.$store.dispatch('creatAccount', {
firstName: this.firstname, 
lastName: this.lastname,
email: this.email,
password: this.password
})
setTimeout(() => { 
// first time submitting the form it display the error message but the second time it doesn't !   
console.log(this.responseErrorMessage)  
}, 2000)
}
}
</script>

Veux:

export default createStore({
state: {
responseSuccessMessage: null,
responseErrorMessage: null
},
mutations: {
SUCCESS_MESSAGE(state, message) {
state.responseSuccessMessage = message
},
ERROR_MESSAGE(state, message) {
state.responseErrorMessage = message
setInterval(() => {
state.responseErrorMessage = null
}, 3000)
}
},
actions: { 
async creatAccount({ context, commit, }, user) {
try {
let result = await axios.post('http://localhost:3001/api/auth/signup', {
firstName: user.firstName,
lastName: user.lastName,
email: user.email,
password: user.password
})
if (result.status === 201) {
commit('SUCCESS_MESSAGE', result.data.message)
// state.responseSuccessMessage = result.data.message
}
} catch (err) {
if (err.response.status === 409) {
context, commit, // Put this line to avoid eslint errors!
commit('ERROR_MESSAGE', err.response.data.message)
} else {
console.log(err)
}
}
}
},
modules: {}
})

请不要在您的突变函数中使用异步方法(setInterval、setTimeout、promise、ajax…(,您可以更改您的代码,代码

ERROR_MESSAGE(state, message) {
state.responseErrorMessage = message
setInterval(() => {
state.responseErrorMessage = null
}, 3000)
}

你可能想将responseErrorMessage重置为null,但方法不正确,你可以这样写:

突变:

ERROR_MESSAGE(state, message) {
state.responseErrorMessage = message
}

全球观察:

responseErrorMessage (New,Old){
if(New){
setTimeout(()=>{
this.$store.commit('ERROR_MESSAGE',null)
},3000)
}
}

你可以试试

最新更新