Vuex的簡單操作

Vuex 的優點

數據倉庫: 集中式存儲
組件通信: 便於在各個組件之間進行數據共享、傳遞
單項數據流: 遵循特定的規則,特定的入口改變數據,特定的出口輸出數據,
同時可監測到數據的變化過程

下載安裝依賴

 npm i vuex -s

Vuex的核心:state,mutation,action,getter,module

state 記錄存儲公共的狀態。
mutation 事件改變state中的狀態,第一個參數是state。
action 處理異步的事件。
getter 類似於計算屬性

Vuex 的輔助函數

import {mapState,mapMutations,mapActions,mapGetters} from "vuex"
state的輔助函數需要映射到計算屬性中computed,
映射的名稱一定要相同,然後就可以通過this訪問到state。
  computed:{
        ...mapState(["name"]),//name和vuex中的state保持一至。
    },
methods:{
  click(){
    console.log(this.name)//訪問到vuex的name
  }
}
mutation的輔助函數mapMutations把mutations裏面的方法映射到methods中。
映射的名稱一定要相同,然後就可以通過this調用mutaition的方法。
 mutations: {
    show(state){
      console.log(state)
    }
  },
 methods:{
        ...mapMutations(["show"]),
        click(){
            this.show()
        },
}
mapAcions:把actions裏面的方法映射到methods中
mapGetters:把getters屬性映射到computed身上

Vuex 如何使用
建立一個store的文件夾,建一個index.js,在main.js裏面全局引入,實例裏面註冊

index.js
import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex)
const mutations={
	add(state,n){
		state.num+=n
	},
	reduce(state,n){
		// 可傳參
		state.num--
	}
}
export default new Vuex.Store({
    state:{
        num:0,
        arr:[]
    },
	// mutations 可以單獨建立js 直接引入
 mutations:{
      add(state){
            state.num++
         },
      reduce(state){
             state.num--
        }
    },
// 	// mutations  異步分發
	actions:{
		addAction(context){
		  context.commit("add")
		},
		reduceAction({commit}){
		   commit("reduce")
		}
	},
	getters:{
		num(state){
			return state.num
		},
		arr(state){
			return state.arr
		} 
	}
})

在組件中的使用

state  
// state  獲取值的方式
//第一種
//      computed:{
//            num(){
//                 return this.$store.state.num
//            }
//      }
// 第二種
//      computed:{
//         ...mapState(['num'])
//      }
//第三種
// computed:mapState(['num'])
getter
// getters 獲取值的方式

// 第一種
// 	computed:{
// 		num(){
// 			return this.$store.getters.num
// 		}
// 	},
// 第二種
// 	computed:{
// 	    ...mapGetters(["num","arr"])
// 	},
//第三種
    computed:mapGetters(["num"]),
// mutations  方法
mapMutations

// 第一種
// 	methods: {
// 		add() {
// 		    this.$store.state.num++
// 		},
// 		reduce(){
// 		    this.$store.state.num--
// 		}
// 	},
// 第二種

//       methods: {
//          ...mapMutations(["add","reduce"])
//       },
     // 第三種
      // methods:mapMutations(["add","reduce"])
第四種
<button @click="$store.commit('add',5)">+</button>
<button @click="$store.commit('reduce',2)">-</button>
mapActions
//第一種方法
<button @click="$store.dispatch('addAction',5)">+</button>
<button @click="$store.dispatch('reduce',2)">-</button>		
// 第二種方法
// 		 methods:{
// 			  ...mapActions(["addAction","reduceAction"])
// 		 }
// 第三種方法
methods:mapActions(["addAction","reduceAction"]),
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章