vuex组件获取state内数据与时时计算的简便写法

效果图如下:
在这里插入图片描述

普通方法:

store.js代码如下:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
	//状态数据
  state: {
		name: '我是store的数据',
		num1: 11,
		num2: 22
  },
	//getters可以认为是store的计算属性
	getters:{
		num1(state){
				return state.num1
		},
		num2(state){
				return state.num2
		},
	},
	//存放同步函数方法
  mutations: {
		//参数1:是状态数据 参数2:n默认为1
		incrementC(state, n=1){
			state.num1 +=n
		},
		//箭头函数写法
		decrementC:(state, n=1)=>{
			state.num2 -=n
		}
  },
	//存放异步函数方法
  actions: {
  }
})

引入store数据组件app.vue代码如下:

<template>
  <div id="app">
		<!-- 匹配到的路由组件 -->
		<!-- <router-view /> -->
		<h1>下面是在created生命周期时获取store内的数据</h1>
		<h3>{{msg}}</h3>
		<hr>
		<h1>下面是获取store内的数据(不是计算属性)</h1>
		<h2>num1:{{num11}} | num2:{{num22}}</h2>
		<hr>
		<h1>下面是执行store内方法改变store内的数据(组件内更改store数据的唯一方法)</h1>
		<h1><input type="button" value="增加num1" @click="incrementC(1)">
		{{num1}}
		<input type="button" value="减少num2" @click="decrementC(1)">
		{{num2}}
		</h1>
  </div>
</template>

<script>
export default {
  name: 'app',
	//这里面存放数据
	data(){
		return{
			msg:'默认值'
		}
	},
	//生命周期函数
	created(){
		this.msg = this.$store.state.name;
		this.num11 = this.$store.state.num1;
		this.num22 = this.$store.state.num2;
	},
	//获取计算数据
	computed:{
		num1(){
			return this.$store.getters.num1;
		},
		num2(){
			return this.$store.getters.num2;
		}
	},
	methods:{
		incrementC(n){
			this.$store.commit('incrementC',n);
		},
		decrementC(n){
			this.$store.commit('decrementC',n);
		}
	}
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

简便方法: (引入vuex辅助函数)

app.vue代码如下:

<script>
//引入vuex辅助函数
import {mapState,mapGetters,mapMutations} from 'vuex'
export default {
  name: 'app',
  components: {

  },
	//这里面存放数据
	data(){
		return{
			msg:'默认值'
		}
	},
	//生命周期函数
	created(){
		this.msg = this.$store.state.name;
		this.num11 = this.$store.state.num1;
		this.num22 = this.$store.state.num2;
	},
	//获取计算数据
	computed: mapGetters(['num1','num2']),
	//获取方法
	methods: mapMutations(['incrementC','decrementC']),
	//上面两种引入可以完全代替下面写法
	//获取计算数据
	// computed:{
	// 	num1(){
	// 		return this.$store.getters.num1;
	// 	},
	// 	num2(){
	// 		return this.$store.getters.num2;
	// 	}
	// },
	// methods:{
	// 	incrementC(n){
	// 		this.$store.commit('incrementC',n);
	// 	},
	// 	decrementC(n){
	// 		this.$store.commit('decrementC',n);
	// 	}
	// }
}
</script>
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值