Vuex的理解及應用

一、Vuex的概述

1.什麼是Vuex?

1. vuex是爲Vue.js應用程序開發的狀態管理模式。採用集中式儲存管理應用所有組件的狀態,並以相應的規則保證狀態已可預測的方式發生變化。
2. 能夠在Vuex集中管理共享的數據,便於開發和後期進行維護。
3. 能夠高效的實現組件之間的數據共享,提高開發效率。
4. 儲存在vuex中的數據是響應式的,當數據發生改變時,頁面中的數據也會同步更新。

2.Vuex的基本使用

  • 安裝
npm install vuex --save
  • 創建store.js文件
import Vue fron 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)
//按需導出
export const store = new Vuex.store({
	state:{
		//數據
	},
	//只有mutations中定義的函數,纔有權力修改state的數據
	mutations:{
		//方法
	},
	actions:{
		methodAsync(context) {
     	// 異步操作
    	},
	},
	getters:{
		//數據加工
	}
	
})
  • 將stroe.js掛載到Vue實例 main.js文件
//按需引入
import { store } from './store/store'

new Vue({
  store,
  router,
  render: h => h(App),
}).$mount('#app')

二、Vuex的核心

1. state

  • state是什麼?

State 提供唯一的公共數據源,所有共享的數據都要統一放到 Store 中的 State 中存儲

  • 獲取state中的數據的方式
//在store.js聲明state
state:{
//數據
}

/**
	方式一
*/
//1.在對應的vue組件中
this.$store.state 全局數據名稱

/**
	方式二
*/
// 1.在對應 vue 組件中導入 mapState
import { mapState } from 'vuex'
// 2. 然後數據映射爲計算屬性
computed:{
	// products(){
	//         // return this.$store.state.products;

	// },
		...mapState([
			"products"
		]),
},

2. Mutation

  • Mutation是什麼

Vuex 不支持直接修改 state 中的數據,需要 Mutation 修改間接 state 中的數據

  • Mutation的使用方式
//1.先在store.js中聲明
mutations:{
	// 參數 1:永遠都是 state 也就是 $state 對象
	// 參數 2:調用方法傳遞的參數,可以沒有
	method(state,step){
    	// 操作
    }
}

/**
	方式一
*/
//在對應的vue組件中使用commit函數調用mutations中對應函數
this.$store.commit('Mutation函數名','參數')

/**
	方式二
*/
//1. 在對應的vue組件中導入mapMutations
import { mapMutations } from 'vuex'

//2.將Mutation 函數映射成methods函數
methods:{
  ...mapMutations(['method'])
}

3. Action

  • Action是什麼?

在 Mutations 中不能編寫異步的代碼,會導致 vue 報錯,vuex 中提供了 Action 來執行異步操作。

  • Action 的使用方式
// 在store.js中聲明異步函數
actions:{
	mthodAsync(context,'參數'){
		//異步操作
}

/**
方式一
*/
// 1.在對應的vue組件中
this.$store.dispatch('異步函數名''參數')

/**
方式二
*/
// 1. 在組件中引入mapActions
import { mapActions } from 'vuex'
// 2. 將 action 函數映射爲 methods 函數
methods:{
	// reducePrice(amount){
	// return this.$store.state.products.forEach(product => {
	//      product.price -= 1
	// })
	//   this.$store.commit('reducePrice')
	//   this.$store.dispatch('reducePrice',amount)
	// }
	...mapActions([
		"異步函數名"
	])
}

4. Getter

  • Getter是什麼?

Getter是用於對store中數據進行加工處理形成新的數據,他只會包裝Store中保存的數據,並不會修改 Store 中保存的數據。 當 Store 中的數據發生變化時,Getter 生成的內容也會隨之變化

  • Getter 的使用方式
// 在 store.js 中添加 getter 屬性
getters:{
	//添加了一個屬性
	屬性名 : state => {
		return "修飾後的內容";
	}
}

/*
	方式一
*/
// 在對應 vue 組件中使用以下方式
this.$store.getters.屬性名

/*
	方式二
*/
// 1. 在對應 vue 組件中引入 mapGetter
import { mapGetters } from 'vuex'
// 2. 將 Getter 屬性映射爲 計算屬性
computed:{
  ...mapGetters(['showNum'])
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章