uniapp vuex状态管理

https://mp.weixin.qq.com/s/tTji00z_gvUVxRAFvR_x0g
https://mp.weixin.qq.com/s/WRt7vK8vx8nKcWUyeZ8R5w
https://mp.weixin.qq.com/s/rOrKmJTkudVfxT8lCOAmbg

main.js

// 调用 store vuex 状态管理,法1
import store from '@/store/index.js'
 //// 调用 store vuex 状态管理,法2
//import store from './store'
// Vue.prototype.$store = store
 new Vue({
   el: '#app',
   store
 })

store/index.vue

const store = new Vuex.Store({
  state: {
    // 管理数据
    count: 0
 }
})

使用

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

唯一改变数据途径mutation,(同步)

mutations: {
    // 方法里参数 第一个参数是当前store的state属性
    // payload 载荷 运输参数 调用mutaiions的时候 可以传递参数 传递载荷
    addCount (state) {
      state.count += 1
    },
    addCount2:(state)=>state.count++
  },

mutation调用

import  { mapMutations } from 'vuex'
methods: {
    ...mapMutations(['addCount'])
}

<button @click="addCount(100)">+100</button>

异步改变action

actions: {
  //  获取异步的数据 context表示当前的store的实例 可以通过 context.state 获取状态 也可以通过context.commit 来提交mutations, 也可以 context.diapatch调用其他的action
    getAsyncCount (context) {
      setTimeout(function(){
        // 一秒钟之后 要给一个数 去修改state
        context.commit('addCount', 123)
      }, 1000)
    }
 }

异步调用action

<button @click="getAsyncCount(111)">+异步</button>
import { mapActions } from 'vuex'
methods: {
    ...mapActions(['getAsyncCount'])
}

getter获取器,数据预处理

getters: {
     // getters函数的第一个参数是 state
     // 必须要有返回值
      filterList:  state =>  state.list.filter(item => item > 5)
  }

getter使用

  <div>{{ filterList }}</div>
import { mapGetters} from 'vuex'
computed: {
     ...mapGetters(['filterList'])
 }
发表新评论