vue2使用vuex

63 阅读1分钟

使用场景:

多组件共享相同的数据状态
原理:

  • state:定义数据
  • getter:类似vue中的computed
  • mutation:修改数据
  • action:异步方法,后执行mutation

ps:只能通过 mutation去修改state里定义的值

安装

npm install vuex

最简单Store

//  src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})
// main.js中注册
new Vue({
  el: '#app',
  store
})
//组件中使用
this.$store.commit('increment')

state部分-定义数据

state中的数据是响应式的,在组件中定义应该在computed中

computed:{
    count(){
      return this.$store.state.count
    }
},

使用对象展开符 简化代码

computed: { ...mapState(['count'])}

getter部分-获取计算后的数据

也是混入到computed中
使用对象展开符 简化代码

//store/index.js
getters: {
    doneTodos (state) {
        return state.todos.filter(todo => todo.done)
    }
},
//组件中 
import { mapState,mapGetters,mapMutations } from 'vuex';
。。。
computed: { ...mapGetters(['dotos'])}

ps:getters中可传递别的getter作为第二个参数

mutation-处理逻辑-同步

同步处理逻辑

//store/index.js
mutations: {
    increment(state,callback) {
        state.count++
        callback()
    }
}
//组件中
methods:{
...mapMutations(['increment']),
add(){
  
  this.increment(()=>{console.log(22)})
}
}

//直接调用
this.$store.commit('increment')

可以接收一个参数

action

//store/index.js
actions:{
    incrementAsync({commit}) {
        setTimeout(()=>{
            commit('increment')
        },2000)
    }
}

//组件中
...mapActions(['incrementAsync']),
addAsync(){
  this.incrementAsync()
}
//直接调用
this.$store.dispatch('increment')

和mutation一样,也可以传递一个参数

model使用 把store分割成模块

//store/index.js
import modelA from './model/user'
const store = new Vuex.Store({
    modules:{
        modelA
    }
})
//组件中使用
computed:{
    ...mapState('modelA',['count']),
    ...mapGetters('modelA',['doneTodos'])
},