vue—vuex

个人理解:vuex状态管理器,常用于系统级的变量。

一.vuex的引入、创建、暴露
1.创建vuex目录结构:

src
--store
--index.js
--modules
--student.js
--class.js

2.main.js全局引入store,如需要个别模块单独使用就在个别模块中引用

import store from './store/index'
const app = new Vue({
  //..
  store, 
  //..
})

3.store文件夹下的index.js,引入vuex并暴露store

import Vue from 'vue'
import Vuex from 'vuex'
import student from './modules/student'
import class from './modules/class'
Vue.use(Vuex)
const store = new Vuex.Store({
   student,
   class
})
export default store

若vuex状态模块很多可以在创建一个modules.js整合vuex各个模块student、class后,在统一在index中引入,方便统一管理。
4.创建两个vuex:

1)student.js
const student = {
  // 命名空间,不配置会报错
  namespaced:true,
  // 定义vuex变量
  state:{
    studentInfo : {}
  },
  // 组件调用改变vuex变量值的唯一方法
  mutations:{
    SET_STUDENTINFO: (state, studentInfo) => {
    state.studentInfo = studentInfo
  }, 
},
// 调用mutations,其他组件可以通过actions中的方法来进行state中值的设置。
actions:{
  setStudentInfo ({ commit }, studentInfo) {
    commit('SET_STUDENTINFO', studentInfo) 
  } 
}
export default student 
2)class.js
const class = {
  // 命名空间,不配置会报错
  namespaced:true,
  // 定义vuex变量
  state:{
    classInfo : {}
  },
  // 组件调用改变vuex变量值的唯一方法
  mutations:{
    SET_CLASSINFO: (state, classInfo) => {
    state.classInfo = classInfo
  }, 
},
// 调用mutations,其他组件可以通过actions中的方法来进行state中值的设置。
actions:{
  setClassInfo ({ commit }, classInfo) {
    commit('SET_CLASSINFO', classInfo) 
  } 
}
export default class 

二.组件中vuex的使用
1.使用vuex中的值

<script>
export default {
  computed: {
    studentInfo: function() {
      return this.$store.state.student.studentInfo
    }
  }
}
</script>

2.更新vuex数据值

dispatch:异步操作,写法:this.$store.dispatch('setClassInfo',classInfo)
commit:同步操作,写法:this.$store.commit('setStudentInfo',studentInfo)
posted @ 2021-02-22 23:30  对月当歌  阅读(92)  评论(0)    收藏  举报