RE: RE: Vue.js实战笔记
You are viewing a single comment's thread from:

RE: Vue.js实战笔记

Words
81
Reading
1 min
Listen
Play
7y

vue配套的公共数据管理工具,它可以把一些共享的数据保存到vuex中,实现不同组件传值,并且数据持久化。

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。小项目可以直接用H5的 localStorage 、 sessionStorage

cnpm install vuex --save

import Vuex from 'vuex'
Vue.use(Vuex)
var store = new Vuex.Store({
  state: {
    count: 0  //this.$store.state.count调用数据
  },
  mutations: {
   increment(state){
     state.count ++
   }, //this.$store.commit('increment')调用方法
   getters:  {
      optCount: function (state) {
        return state.count   //只对外提供数据,$store.getters.optCount
      }
   }
  }
})
//挂载到VM实例上
var app = new Vue({
        el: '#app',
        store
      })  

总结:
1. state中的数据,不能直接修改,如果想要修改,必须通过 mutations
2. 如果组件想要直接 从 state 上获取数据: 需要 this.$store.state.***
3. 如果 组件,想要修改数据,必须使用 mutations 提供的方法,需要通过 this.$store.commit('方法的名称', 唯一的一个参数(可以拼成对象))
  that.$store.commit('saveUser', {username: that.username, password: privWif})
4. 如果 store 中 state 上的数据, 在对外提供的时候,需要做一层包装,那么 ,推荐使用 getters, 如果需要使用 getters ,则用 this.$store.getters.***
@lemooljiang: | Ecency