vuex使用的简单例子

vuex的基本知识讲解


store.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

export const store = new Vuex.Store({
	state: {
		lists: [{
			id: 1,
			name: '你好,Vuex',
			money: 122
		}]
	},
	getters: {
		lists2: (state) => {
			var numArr = state.lists.map(num => {
				return {
					id: new Date(),
					name: "**" + num.name + "**",
					money: num.money / 2
				}
			})
			return numArr
		}
	},
	mutations: {
		reducePriceM: (state, payload) => {
			state.lists.forEach(num => {
				num.money -= payload;
			})
		}
	},
	actions: {
	//payload是参数,可以是对象
		reducePriceA: (context, payload) => {
			context.commit('reducePriceM', payload)
		}
	}
})

调用方式如下:
Test.vue

<template>
	<div>
		<div v-for="(item,index) in lists" :key="index">{{item.name}}&nbsp;{{item.money}} </div>
		<button @click="reducePriceA(4)">商品降价</button>
	</div>
</template>

<script>
	import {mapState,mapGetters,mapActions} from 'vuex'
	export default {
		computed: {
			...mapState({
				lists:state => state.lists
			}),
			...mapGetters([
				"lists2"
			])
		},
		methods: {
			...mapActions([
				"reducePriceA"
			])
		}
	}
</script>

<style>
</style>


如果没有写mapState,可以获取state中的属性值,

computed:{
	lists() {
		console.log(this.$store)
		return this.$store.state.lists
	}
}

如果在store.js中没有写mapGetters,我们可以使用如下方式获取getters:

computed:{
	lists2() {
		return this.$store.getters.lists2;
	}
}

如果没有在store.js中写mutations:

computed:{
	lists2() {
		var numArr = this.$store.state.lists.map(num => {
			return {
				id: new Date(),
				name: "**"+num.name+"**",
				money: num.money / 2
			}
		})
		return numArr
	}
}

没有写mapActions:可以使用如下:

methods:{
	reducePriceX(amount) {
		/* this.$store.state.lists.forEach(num=>{
				num.money-=1;
		}) */
		 this.$store.commit('reducePrice')
		this.$store.dispatch("reducePriceA", amount); //分发actions
	}
}

注意:
对象展开运算符什么时候使用:
mapState、mapGetters、mapActions

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值