action

  • 在action 中执行异步操作,向后台请求数据 并存放到state 中
  • 调用: dispatch
export default new Vuex.Store({
    state: {
        username,
        token,
        accpng
    },
    mutations: {
        setUserInfo(state, payload) {
            const {
                username,
                token
            } = payload
            state.username = username
            state.token = token
        }
    },
    actions: {
        asyncLogin(ctx, payload) {
            axios('url/login', payload).then(res => {
                // 登录成功  调用 mutations 存储state  
                ctx.commit('setUserInfo', res)
            })
        },

        // 解构 {commit}
        asyncLogina({commit}, payload) {
            axios('url/login', payload).then(res => {
                // 登录成功  调用 mutations 存储state  
               commit('setUserInfo', res)
            })
        }
    },
    getters: {},
    modules: {}
})

调用

export default{
  // 在需要的地方调用
   mounted(){
    let payload ={
      key,password,username,token
    }
    this.$store.dispatch('asyncApi',payload)
  }
}