vue--day73--getters的使用

发布时间 2023-08-27 02:00:02作者: 雪落无痕1

1. 概念:当state中的数据需要经过加工后再使用时,可以使用getters加工。

 

2. 在```store.js```中追加```getters```配置

 

   ```js

   ......

   

   const getters = {

   bigSum(state){

   return state.sum * 10

   }

   }

   

   //创建并暴露store

   export default new Vuex.Store({

   ......

   getters

   })

   ```

 

3. 组件中读取数据:```$store.getters.bigSum```

 

 

4. store/index.js

//改文件用于创建vuex 最为核心的 store
import Vue from 'vue'
//引入vuex
import Vuex from 'vuex'
Vue.use(Vuex)
// 准备actions ---用于响应组件中的动作
const actions={
// 没有逻辑 可以直接 mutations
// jia(conext,value){
// //console.log("actions里面的jia被调用了",conext,value)
// conext.commit('JIA',value)
// },
// jian(conext,value){
// //console.log("actions里面的jian被调用了",conext,value)
// conext.commit('JIAN',value)
// },
incrementOdd(conext,value){
//console.log("actions里面的incrementOdd被调用了",conext,value)
 
if(conext.state.sum%2){
conext.commit('JIA',value)
}

},

incrementWait(conext,value){
//console.log("actions里面的incrementWait被调用了",conext,value)
 
setTimeout(() => {
conext.commit('JIA',value)
}, 500);
 

},
 

 
}
//准备mutations--用于操作数据(state)
const mutations={
JIA(state,value){
//console.log("mutations里面的jia被调用了",state,value)
state.sum+=value
},
JIAN(state,value){
//console.log("mutations里面的jian被调用了",state,value)
state.sum-=value
},
}
//准备state --用于存储数据
const state={
sum:0
}
// 准备getters 用于将state 中的数据进行加工
const getters = {
bigSum(state){
return state.sum * 10
}
}
// 创建store 暴露store
export default new Vuex.Store({
actions,
mutations,
state,
getters
})
5. Count.vue
<template>
<div>

<h1>当前求和位{{ $store.state.sum }}</h1>
<h1>当前求和放大10倍后是{{ $store.getters.bigSum }}</h1>
<select v-model.number="n">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<button @click="increment">+</button>
<button @click="dectement">-</button>
<button @click="incrementOdd">当前和为奇数在加</button>
<button @click="incrementWait">等一等在加</button>
</div>
</template>

<script>
export default {
name:'Count',
data(){
return {
n:1,
sum:0
}
},
mounted(){
console.log('countvue',this)
},
methods:{
increment(){
//this.$store.dispatch('jia',this.n)
this.$store.commit('JIA',this.n)
},

dectement(){
 
//this.$store.dispatch('jian',this.n)
this.$store.commit('JIAN',this.n)
},
incrementOdd(){
this.$store.dispatch('incrementOdd',this.n)
},
incrementWait(){
this.$store.dispatch('incrementWait',this.n)
}

}
}
</script>

<style>
button{
margin-left: 10px;
}

</style>
6. App.vue
<template>
<div>
<Count></Count>
</div>
 
 
</template>
 
<script>
import Count from './components/Count.vue';
export default {
name: 'App',
components:{
 
Count
},
mounted(){
console.log('appvue',this)
}
 
}

</script>

<style>

</style>