019-Vuex狀態管理

一、Vuex簡介

vue應用程序的狀態管理模式。他採用集中式存儲管理應用的所有組件的狀態,
並以相應的規則保證狀態以一種可預測的方式發生變化。
vuex包含部分

  1. View
  2. Actions
  3. Mutations
  4. State在這裏插入圖片描述
    一句話總結上圖:
    Vuex模塊間可以共享狀態。vue組件dispatch發送事件觸發Actions,
    Actions可以進行異步請求,再去觸發Mutations,Mutations只可以
    同步操作倉庫中的數據

二、安裝

npm install vuex --save
若開發的是多頁面,且使用的vue是通過script引入的,那麼在引入vue.js
之後再引入vuex.js。

三、使用

1、在入口文件main.js中引入

import Vuex from ‘vuex’;

2、全局註冊使用

Vue.use(Vuex);

3、實例化數據中心store
import Vue from 'vue';
import Vuex from 'vuex';
import Store from './store';
...
// 溫馨提示:只有在導入vue、vuex之後才能實例化store
let store = new Vuex.Store(Store);
...

若數據量比較大時,可以將store單獨抽取爲一個模塊。
下面是官方給出結構示例:
https://vuex.vuejs.org/zh/guide/structure.html
在這裏插入圖片描述
在官方給出結構的基礎上剝離了state,把他和actions放在同一文件層級下。
A、index.js 導出store。

import state from './state';
import getters from './getters';
import actions from './actions';
import mutations from './mutations';
export default {
	state ,
	getters ,
	actions ,
	mutations 
};

B、state.js

export default {
	orderList: [],
	params: {}
}

C、actions.js 異步請求api接口

const actions = {
	fetchOrderList ({ commit , state}) {
		axios.get('/api/getOrderList', { state.params } )
		.then(res => {
			commit('updateOrderList' ,  res.data.list);
		}).catch(err => {
			
		})
	}
}

D、mutations.js 同步動作

const mutations = {
	updateOrderList (state , payLoad) {
		state.orderList = payLoad;
	},
	/*updateParams (state , payLoad ) {
		state.params[payLoad.key] = payLoad.val; 
	},*/
	updateParams (state , { key ,val } ) {
		state.params[key] = val; 
	},
}

E、getters.js 獲取state的數據

const getters = {
	getOrderList: state => state.orderList
}
4、放到vue實例中使用
 new Vue({
	el: '#app' ,
	store ,
	router , 
	component: { Layout } ,
	template: '<Layout />'
});
5、組件中使用store的方法
1、異步數據更改
A、計算屬性
computed () {
	// 動態的獲取數據
	tableData () {
		// this.$store store對象
		return this.$store.getters.getOrderList
	}
}
B、主動調用actions進行賦值
mounted () {
	// 請求結果的修改
	this.$store.dispatch('fetchOrderList ');
}
C、組件的渲染
<view v-for="item in tableData" >
	<view>{{ item.name }}</view>
</view>
2、同步數據的更改
A、結構
<view v-for="item in ['m','w']" @click='changeType(item)'>類型更改</view>
B、初始化type值
data () {
	return {
		type: 'm'
	}
}
C、更改type值的邏輯處理
methods	{
	changeType (str) {
		this.$store.commit('updateParams',{
			key: 'type', // data對象下要更改的屬性名
			val: str
		});
		this.$store.dispatch('fetchOrderList ');
	},
}

dispatch、commit等方法詳情,請查看官方文檔:
https://vuex.vuejs.org/zh/api/#vuex-store

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章