Vuex(一):State和Mutation

Vuex(一):State和Mutation

官方解释:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。

它采用 集中式存储管理 应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

个人理解:Vuex把组件间需要共享的变量全部存储在一个对象里面,然后将这个对象放在顶层组件中供其他组件使用,让需要被共享的变量被统一管理并且达到响应式的效果。

【Vuex的安装过程】

  • 新建完vuecli项目后执行命令npm install vuex --save
  • 在src文件夹下新建store文件夹,一般不改名,固定命名store(仓库)
  • 在store文件夹下新建index.js
  • 在mian.js文件下引入store即引入index.js
     1 import Vue from 'vue'
     2 import App from './App'
     3 import store from './store'
     4 
     5 Vue.config.productionTip = false
     6 
     7 /* eslint-disable no-new */
     8 new Vue({
     9   el: '#app',
    10   store,
    11   render: h => h(App)
    12 })
  • 初始化index.js
    import Vue from 'vue'
    import Vuex from 'vuex'
    
    // 安装插件
    Vue.use(Vuex)
    
    // 创建Vuex对象,一般命名为store
    const store = new Vuex.Store({
      // state: 存储状态,变量
      state: {},
      // mutations: mutations是store状态的更新唯一方式,内部定义有关修改state的方法,this.$store.commit('方法名', 可选参数)进行调用
      mutations: {},
      // getters: 派生状态,类似computed计算属性,$store.getters.属性名 进行调用
      getters: {},
      // actions: 类似mutations,但支持异步操作,$store.dispatch('方法名', 可选参数)进行调用
      actions: {},
      // modules: store的子模块,内容就相当于是store的一个实例。调用前加上子模块名
      modules: {}
    })
    
    // 导出store
    export default store

    至此为止vuex初始完毕,后续在.vue文件中$store使用store对象

【state】

   state用于存储状态,变量

 App.vue中访问state中的变量

<h2>----------App中直接访问state中的变量----------</h2>
<h2>{{$store.state.counter}}</h2>

  子组件中访问state中的变量

<h2>{{$store.state.counter}}</h2>

  state中所有变量都必须通过mutations中定义的方法进行修改

【mutations】

  mutations是store状态的更新唯一方式,内部定义有关修改state的方法,this.$store.commit('方法名', 可选参数)进行调用

  • 不传参数的情况
    // vue文件中methods用commit调用mutations中的方法
    methods: {
        addition () {
          this.$store.commit('addone')
        },
        subtraction () {
          this.$store.commit('subone')
        }
      }
    // mutations中方法的第一个参数必定为state,以此修改state中的变量的值
    mutations: {
        addone (state) {
          state.counter ++
        },
        subone (state) {
          state.counter --
        }
      }
  • 传参数的情况
    // 所传参数放置于commit括号内方法名后
    methods: {
        addCount (counts) {
          this.$store.commit('incrementCount', counts)
        }
      }
    // mutations内正常调用
    mutations: {
        incrementCount (state, counts) {
          state.counter += counts
        }
      },

    参数也可传对象

    // 传参(对象)
    addStudent () {
       const stu = {id: 115, name: 'jack', age: 31}
       this.$store.commit('addStudent', stu)
    }
    
    //接收
    addStudent (state, stu) {
       tate.students.push(stu)
    }

  

猜你喜欢

转载自www.cnblogs.com/xzweb/p/12417780.html