基本上我正在使用Vue 3,并且我尝试分配服务器返回的错误,例如,如果电子邮件已被其他用户占用。第一次工作正常时,我可以将服务器返回的消息分配给我的 state.responseErrorMessage
属性,但是当我尝试使用新电子邮件重新发送而不刷新页面时,ERROR_MESSAGE 突变不会更新!
<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>
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: {} })
请不要在你的mutation函数中使用异步方法(setInterval、setTimeout、promise、ajax...),你可以改变你的代码,代码
你可能想将responeErrorMessage重置为null,但是方式不对,你可以这样写:
突变:
全球观察:
你可以试试