Nunca he usado Vuex con Nuxt.js , así que encontré el problema. Aquí está mi archivo store/index.js :
export const state = () => ({ wrongCredentials: false, logged: false, uxd: null }) export const mutations = { setWrongCredentials(state, value) { state.wrongCredentials = value }, setLogged(state, value) { state.logged = value }, setUxd(state, value) { state.uxd = value }, }Como puede ver, hay estado y mutaciones. En mi otro archivo, donde verifico el token JWT del usuario y, dependiendo del resultado, quiero establecer valores en la tienda:
import jwt from 'jsonwebtoken' import cert from '../jwt/public' export default { verify (token) { jwt.verify(token, cert, async (err, decoded) => { if (err) { this.$store.state.wrongCredentials = true this.$store.state.logged = false this.$store.state.uxd = null } else { this.$store.state.wrongCredentials = false this.$store.state.logged = true this.$store.state.uxd = decoded.uxd } }) } }El código que ves no funciona correctamente, simplemente no establece valores, así que creé mutaciones e hice algo como esto:
await this.$store.dispatch('setWrongCredentials', true)
Tampoco funciona. El problema es que no sé cómo trabajar con la tienda Vuex , no en archivos .vue , entonces, ¿cómo puedo establecer valores en la tienda?
Desafortunadamente, no he encontrado la solución a este problema como quería en el archivo .js , así que aquí hay otra solución.
En primer lugar, debe establecer no solo el estado y las mutaciones, sino también las acciones:
export const actions = { fetchWrongCredentials(ctx, value) { ctx.commit('setWrongCredentials', value) }, fetchLogged(ctx, value) { ctx.commit('setLogged', value) }, fetchUxd(ctx, value) { ctx.commit('setUxd', value) } } Y en su componente Vue necesita establecer valores en estado usando acciones, así:
methods: { ...mapActions(['fetchWrongCredentials', 'fetchLogged', 'fetchUxd']), async login() { await login({ password: this.userPassword, login: this.userLogin, twoFactor: this.twoFactor }).then(result => { const jwtRes = jwt.verify(result.token) this.fetchLogged(true) this.fetchWrongCredentials(false) this.fetchUxd(jwtRes.token) }).catch(() => { this.fetchLogged(false) this.fetchWrongCredentials(true) this.fetchUxd(null) this.error = true setTimeout(() => { this.error = false }, 1000) }) } } En mi caso, tuve que modificar ese archivo .js :
import jwt from 'jsonwebtoken' import cert from '../jwt/public' export default { verify (token) { return jwt.verify(token, cert, (err, decoded) => { if (err) { return false } else { return { token: decoded.uxd } } }) } }