【Vue2】vuex的基本使用

vuex-Vue.js 的中心化状态管理方案

主要包含State, Getter, Mutations,Actions, Module。

State

存储状态数据,可以直接设置和获取状态值。

结构

state: {
  token: "xxxx"
},

使用

设置值
this.$store.state.token = "xxxx"
获取值
let token = this.$store.state.token

注意事项
data() {
  return {
    token:this.$store.state.token,  
  }
}
//如果这样写值更新不了
//这里需要把store 动态的数据放到computed里面才会同步更新 视图
computed:{
 两种方法
1.
  getToken(){
     return this.$store.state.token
   }
2.
  mapState{["token"]}
},

Getter

用于获取需要处理的状态,例如:等级值为1,返回初级战士。

结构

state: {
  level: 1
},
getters: {
  level: state => {
    let level = ""
    swicth(state.level){
      case 1:
        level = "初级战士"
        break;
      case 2:
        level = "中级战士"
        break;
      case 3:
        level = "高级战士"
        break;
    }
    return: level
  }
}

使用

1.
this.$store.getters.level
2.
...mapGetters([
      'level',
      // ...
    ])

Mutations

需要对多个状态值进行修改,并且触发页面刷新。

结构

mutations: {
    SET_TOKEN: (state, userData) => {
      state.token = userData.token
      state.level = userData.level
    },
    LOGIN:(state,userData) => {
     ...
    },
    LOGOUT:(state,userData) => {
     ...
    },
  },

使用

this.$store.commit('SET_TOKEN',userData)

Actions

处理异步操作,例如:接口请求

结构

actions: {
    // 登录
    Login({commit}, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo.user, userInfo.password).then(res => {
          if(res.code==200){
            console.log("登录成功")
            commit('SET_TOKEN', res.data )
            resolve();
          }else{
            reject(res.message)
          }
        }).catch(error => {
          console.log("登录失败")
          reject(error)
        })
      })
    },
  }

使用

1.
this.$store.dispatch('Login',userInfo).then(() => {
  ···登录处理           
})
2.
methods:{
  ...mapActions([
    'Login'
  ]),
  changeLogin(){
    this["Login"](userInfo)
  },
}

Module

由于使用单一状态树,应用的所有状态会集中到一个比较大的对象。当应用变得非常复杂时,store 对象就有可能变得相当臃肿。

结构

const moduleA = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: () => ({ ... }),
  mutations: { ... },
  actions: { ... }
}

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})
export default store
store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态

使用

computed: {
  ...mapState('a', {
    state: state => state
  })
},
 methods: {
    // test1 模块路径名
    ...mapActions('a', [
      '...'
    ]),
    changeLogin(){
      this["..."]('ok, a is login !!')
    },
}

更详细的用法还在摸索中,有问题欢迎指出~

猜你喜欢

转载自blog.csdn.net/sky529063865/article/details/118829702