切换到Vuejs中的模块模式VUEX.STORE



我正在寻找vuejs中Vuex商店模块模式的解决方案。因为我使用nuxtjs,因此默认存储将处于经典模式。

我遵循此指令:https://nuxtjs.org/guide/vuex-store#modules-mode,但不起作用。

希望你的家伙能帮助我!

〜/store/index.js

export const AuthenticationStore = new Vuex.Store({
    state: {
      authUser: null,
      userInfo: null,
      token: null
    },
    mutations: {
      SET_USER: function (state, user) {
        state.authUser = user
      },
      SET_TOKEN: function (state, token) {
        state.token = token
        instance.defaults.headers = { Authorization: 'Bearer ' + token }
      }
    },
    actions: {
      async nuxtServerInit ({ commit }, { req }) {
        try {
          const jwtCookie = req.headers.cookie.split(';').find(c => c.trim().startsWith('token='))
          if (jwtCookie) {
            let token = jwtCookie.split('=')[1]
            let payload = jwtDecode(token)
            let date = Date.now() / 1000
            if (payload.exp > date) {
              commit('SET_USER', payload)
              commit('SET_TOKEN', token)
              instance.defaults.baseURL = backendURL
            }
          }
        } catch (error) {
          console.log('nuxtServerInit Failed')
        }
      },
      async login ({ commit }, { username, password }) {
        try {
          const { data } = await axios.post('http://localhost:8000/api/v1/api-token-auth/login', {
            username,
            password
          })
          let payload = jwtDecode(data.token)
          Cookie.set('token', data.token, {
            expires: null
          })
          commit('SET_TOKEN', data.token)
          commit('SET_USER', payload)
        } catch (error) {}
      },
      async logout ({ commit }) {
        Cookie.remove('token')
        commit('SET_USER', null)
        commit('SET_TOKEN', null)
        window.location.href = '/'
      }
    },
    modules: {
      ...
    }
  })

错误:

[vuex] unknown action type: login当组件中的调度操作时:

async login () {
      try {
        await this.$store.dispatch('login', {
          username: this.signupUsername,
          password: this.signupPassword
        })
        this.signupUsername = ''
        this.signupPassword = ''
      } catch (e) {}
    }

我想用Write export const store切换到模块,以便将const存储导入我的项目中的其他JS文件。

由于您使用的是模块化方法,因此您需要添加{ root : true}来访问根操作,突变,getters等。例如:

$ store.dispatch('login',{username:this.signupusername,密码: this.signuppassword},{root:true}(

`

最新更新