什么是Vuex
- Vuex是专门为Vue.js设计的状态管理库
- Vuex采用集中式的方式存储需要共享的状态
- Vuex的作用是进行状态管理,解决复杂组件通信,数据共享
- Vuex集成到了devtools,提供了time-travel时光旅行历史回滚功能
什么情况下使用Vuex
- 非必要的情况不要使用Vuex
- 大型单页应用程序
mapState: 获取到state
computed: {//...mapState(["count"]),...mapState({num:"count"})}
getter
new Vuex.store({state: {count: 0},getters: {reverseCount(state){return state.count++;}}});//$store.getters.reverseCount
mapGetters
computed: {...mapGetters(["count"])}
mutations
mutations:{increate(state,payload) {state.count += payload}}//$store.commit("increate", 2)
mapMutations
methods:{...mapMutations(["increate"])}
actions
increateAsync (context,payload) {setTimeout(() => {context.commit("increate",payload)},2000);}//$store.dispatch("increateAsync", 5)
mapActions
methods:{...mapActions(["increateAsync"])}
modules模块
每个模块都有自己的state/getter/mutations…
还可以给模块添加nameSpaced
Plugin
const myPlugin = store => {store.subscribe((mutation, state) => {if(mutation.type.startsWith("cart/")) {window.localStorage.setItem("cart-products", JSON.stringify(state.cart.cartProducts))}})}new Vuex.store({state: {count: 0},plugins: [myPlugin]});
