极客时间-第二章

321 阅读1分钟

为什么需要Vuex

(1)传参的方法对于多层嵌套的组件将会非常繁琐
(2)我们经常会采用父子组件直接引用或者通过事件来变更和同步状态的多份拷贝。以上的这些模式非常脆弱,通常会导致无法维护的代码

Vuex使用机制

单项数据流相关: 数据-》视图-》操作
(1)state(Render)->Vue Comp(Dispatch)->Action(commit)异步相关->Mutations(Mutate)做些记录
(2)state(Render)->Vue Comp(commit)->Mutations(Mutate)

如何在Vue中使用Vuex?

(1)安装:npm install vuex
(2)使用:
创建数据进行展示
##main.js   
        import Vuex from 'vuex'
        Vue.user(Vuex )
        const store = new  Vuex.Store({
            state:{
                count:0
            }
        })
    	new Vue({
    	  store
    	})
##App.vue
        {{count}}
    	computed:{
    		count(){
    		return this.$store.state.count
    		}
    	}
操作数据同步数据
##App.vue
    @click="$store.commit('fn',1)"
##main.js
	mutations:{
		fn(state,num){
		    state.count+=num;
		}
	},
操作数据异步数据
##App.vue
    @click="$store.dispatch('fn',1)"
	actions:{
		fn({state},num){
		   setTiomeout(()=>{
		     state.count+=num;
		    })
		}
	}
获取数据功能
##main.js
  getters:{
	 doubleCount(state){
  		    return state.count*2
		}
}
##app.vue
{{$store.getters.doubleCount}}