天天看點

Vue入門025- 求和案例_vuex版(getters的使用)

作者:CShap新勢力

getters的使用

概念:當state中的資料需要經過加工後再使用時,可以使用getters加工。

在store.js中追加getters配置

const getters = {
	bigSum(state){
		return state.sum * 10
	}
}           

建立并暴露store

export default new Vuex.Store({
	......
	getters
})           

元件中讀取資料:$store.getters.bigSum

Vue入門025- 求和案例_vuex版(getters的使用)

就是這樣的關系

store/index.js

//該檔案用于建立Vuex中最為核心的store
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//應用Vuex插件
Vue.use(Vuex)

//準備actions——用于響應元件中的動作
const actions = {
	/* jia(context,value){
		console.log('actions中的jia被調用了')
		context.commit('JIA',value)
	},
	jian(context,value){
		console.log('actions中的jian被調用了')
		context.commit('JIAN',value)
	}, */
	jiaOdd(context,value){
		console.log('actions中的jiaOdd被調用了')
		if(context.state.sum % 2){
			context.commit('JIA',value)
		}
	},
	jiaWait(context,value){
		console.log('actions中的jiaWait被調用了')
		setTimeout(()=>{
			context.commit('JIA',value)
		},500)
	}
}
//準備mutations——用于操作資料(state)
const mutations = {
	JIA(state,value){
		console.log('mutations中的JIA被調用了')
		state.sum += value
	},
	JIAN(state,value){
		console.log('mutations中的JIAN被調用了')
		state.sum -= value
	}
}
//準備state——用于存儲資料
const state = {
	sum:0 //目前的和
}
//準備getters——用于将state中的資料進行加工
const getters = {
	bigSum(state){
		return state.sum*10
	}
}

//建立并暴露store
export default new Vuex.Store({
	actions,
	mutations,
	state,
	getters
})           

代碼解釋

//準備getters——用于将state中的資料進行加工
const getters = {
	bigSum(state){
		return state.sum*10
	}
}           

getters 相當于把 state中的資料加工了一下,類型vue中的計算屬性

Count.vue元件

<template>
	<div>
		<h1>目前求和為:{{$store.state.sum}}</h1>
		<h3>目前求和放大10倍為:{{$store.getters.bigSum}}</h3>
		<select v-model.number="n">
			<option value="1">1</option>
			<option value="2">2</option>
			<option value="3">3</option>
		</select>
		<button @click="increment">+</button>
		<button @click="decrement">-</button>
		<button @click="incrementOdd">目前求和為奇數再加</button>
		<button @click="incrementWait">等一等再加</button>
	</div>
</template>

<script>
	export default {
		name:'Count',
		data() {
			return {
				n:1, //使用者選擇的數字
			}
		},
		methods: {
			increment(){
				this.$store.commit('JIA',this.n)
			},
			decrement(){
				this.$store.commit('JIAN',this.n)
			},
			incrementOdd(){
				this.$store.dispatch('jiaOdd',this.n)
			},
			incrementWait(){
				this.$store.dispatch('jiaWait',this.n)
			},
		},
		mounted() {
			console.log('Count',this.$store)
		},
	}
</script>

<style lang="css">
	button{
		margin-left: 5px;
	}
</style>
           

<h3>目前求和放大10倍為:{{$store.getters.bigSum}}</h3>

從store.getters 身上擷取資料

代碼摘錄于尚矽谷Vue學習課件