https://mp.weixin.qq.com/s/tTji00z_gvUVxRAFvR_x0g
https://mp.weixin.qq.com/s/WRt7vK8vx8nKcWUyeZ8R5w
https://mp.weixin.qq.com/s/rOrKmJTkudVfxT8lCOAmbg
// 调用 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
})
const store = new Vuex.Store({
state: {
// 管理数据
count: 0
}
})
import { mapState } from 'vuex'
computed: {
...mapState(['count'])
}
mutations: {
// 方法里参数 第一个参数是当前store的state属性
// payload 载荷 运输参数 调用mutaiions的时候 可以传递参数 传递载荷
addCount (state) {
state.count += 1
},
addCount2:(state)=>state.count++
},
import { mapMutations } from 'vuex'
methods: {
...mapMutations(['addCount'])
}
<button @click="addCount(100)">+100</button>
actions: {
// 获取异步的数据 context表示当前的store的实例 可以通过 context.state 获取状态 也可以通过context.commit 来提交mutations, 也可以 context.diapatch调用其他的action
getAsyncCount (context) {
setTimeout(function(){
// 一秒钟之后 要给一个数 去修改state
context.commit('addCount', 123)
}, 1000)
}
}
<button @click="getAsyncCount(111)">+异步</button>
import { mapActions } from 'vuex'
methods: {
...mapActions(['getAsyncCount'])
}
getters: {
// getters函数的第一个参数是 state
// 必须要有返回值
filterList: state => state.list.filter(item => item > 5)
}
<div>{{ filterList }}</div>
import { mapGetters} from 'vuex'
computed: {
...mapGetters(['filterList'])
}