vuex的使用

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。Vuex 也集成到 Vue 的官方调试工具 devtools extension,提供了诸如零配置的 time-travel 调试、状态快照导入导出等高级调试功能。
vuex有四大金刚:store,actions,getters,mutations;
store:是数据对象;
getters:用法相当于vue组件里面的computed;
mutations:修改store;
actions:也可以修改store,跟mutations不一样的地方是,mutations只能同步修改store,actions可以异步;

一个简单的store.js;

import vue form 'vue';
impot vuex from 'vuex';

Vue.use(Vuex);

let store=new Vuex.Store({
	state:{
		count:0,
		firstName:"Xie",
		lastName:"Bessic"
	},
	getters:{
		fullName: state => {
       			 return `${state.firstName} ${state.lastName}`
   		 }
	},
	actions:{
		addCount({ commit, state }, num) {
        		commit('updataCount', num)
    	}
	},
	munations:{
		updataCount(state, num) {
        	state.count = state.count + num;
        	/**
        	mutations里的方法只接受两个参数,第一个是state,第二个参数是要传进来的数据,文档中的说第二个参数是载荷(Payload);
        	在大多数情况下,载荷应该是一个对象,这样可以包含多个字段并且记录的 mutation 会更易读;
        	**/								
    	},
	}
})
export default store;

引入,在入口js文件

import store from XXX;
new Vue({
    el: '#app',
    router,
    store,
    components: { App },
    template: '<App/>'
})

在vue组件里面引用(基础版)

const Counter = {
	  template: `<div>
			<div> count:{{ count }}</div>
			<div> count:{{ fullName}}</div>
			<div @click='add'>按钮+2</div>
			<div @click='addAction'>用actions</div>
		</div>`,
	 methods:{
			add(){
				this.$commit('updataCount',5)
				//要调用mutations的方法都用this.$commit调起,
			//this.$commit第一个参数是调起的方法,第二个参数是要传给这	个mutations的参数;
			//如果要传多个数据给mutations,可以传一个对象处理;如this.$commit('updataCoun',													//{num:6,type:1}
			},
			addAction(){
				this.dispatch('addCount',9)
			}
		},
	  computed: {
	    count () {
	      return this.$store.state.count
	    },
	
	    fullName(){
			return this.$sotre.getters.fullName;
		}
	  }
}

在vue组件里面引用(简化版)
mapState,mapMutations,mapGetters,mapActions

import {mapState,mapMutations,mapGetters,mapActions} from 'vuex';
const Counter = {
	template: `<div>
							<div> count:{{ count }}</div>
							<div> count:{{ fullName}}</div>
							<div @click='add'>按钮+2</div>
				</div>`,
	methods:{
		...mapActions(['updataCount']),
		...mapMutations(['updataCount']),
        addCount(num){
            this.addCount(num);
            this.updateCount(num);
        },
	},
	computed: {
	    ...mapState([count]),
	    ...mapGetters([fullName'']),
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值