vuex基本使用

作用

状态管理

安装

npm install vuex

使用

src目录中创建store文件夹,以及其下的index.js文件
//index.js文件
import Vue from 'vue';
import Vuex from 'vuex';
import home from './modules/home';

Vue.use(Vuex);

const store = new Vuex.Store({
	// 存放状态
	state: {
		count: 0,
		array: [1,2,3,4,5,6],
		obj: {
			child: {
				name: 'lisi'	
			}	
		}
	},
	//	存放使用次数较多的函数,或者状态(state)层级太多后,用于简化引用。
	getters: {
		newArray(state, getters) {
			return state.array.filter(item => item > 3);
		},
		name(state) { // 效果等同 this.$store.state.obj.child.name
			return state.obj.child.name 	
		}
	},
	// 用于修改状态(state),mutation方法常为同步方法。
	mutations: {
		increment(state, data) {// 其第一个参数是state,第二个是额外参数,由调用者传入
			state.count += data.count;
		}
	},
	// 常用于执行异步方法,执行完毕后调用mutations中相对应的方法变更状态(state)
	actions: {
		simulate(context) { // context == store,但是 context !== store
			return new Promise(resolve => {
				setTimeout(() => {
					context.commit('increment'); // 调用mutations中的方法修改状态。
					resolve(context.state.count);
				}, 2000)	
			})
		}
	},
	// 应用较为复杂有很多状态的时候,可以使用模块化,将状态进行分割。
	modules: {
		home
	}
})
main.js
import store from './store/index';

new Vue({
	el: '#app',
	store
})

组件中如何调用

// 调用state
this.$store.state.xxx
// or
import { mapState } from 'vuex';
computed: {
	...mapState(['xxx'])
}

// 调用getter
this.$store.getters.xxx
// or
import { mapGetters } from 'vuex';
computed: {
	...mapGetters (['xxx'])
}
// 调用mutation
this.$store.commit('xxx');
// or
import { mapMutations } from 'vuex';
methods: {
	...mapMutations (['xxx'])fn() {
		this.xxx();
	}
}

// 调用action
this.$store.dispatch('xxx');
// or
import { mapActions } from 'vuex';
methods: {
	...mapActions (['xxx'])fn() {
		this.xxx();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值