vuex的求和案例和mapstate,mapmutations,mapgetters

main.js

import Vue from 'vue'
import App from './App.vue'
//引入vuex
import Vuex from 'vuex'
//引入store
import store from './store/index'

Vue.config.productionTip = false



new Vue({
    el:"#app",
    render: h => h(App),
    store,
    beforeCreate(){
        Vue.prototype.$bus = this
    }
})

App.vue

<template>
	<div class="container">
		<Count/>
	</div>
</template>

<script>
	import Count from './components/Count'
	export default {
		name:'App',
		components:{Count},
		mounted(){
			console.log('App',this)
		}
	}
</script>

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.dispatch('jia',this.n)
			},
			decrement(){
				this.$store.dispatch('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>
	button{
		margin-left: 5px;
	}
</style>

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配置项

当一部分的数据进行一些变化时,可以通过getters的属性来对一部分的数据进行变化

mapState,mapGetters

// sum(){
			// 	return this.$store.state.sum
			// },
			// school(){
			// 	return this.$store.state.school
			// },
			// subject(){
			// 	return this.$store.state.subject
			// },
			// bigSum(){
			// 	return this.$store.getters.bigSum
			// },

			//借助mapState生成计算属性,从state读取数据(对象写法)
			//  ...mapState({he:'sum',xuexiao:'school',xueke:'subject'})

			//借助mapState生成计算属性,从state中读取数据(数组写法)
			 ...mapState(['sum','school','subject']),

			 ...mapGetters(['bigSum'])

通过计算属性来改变。

mapMutations

在methods方法下

            // increment(){
			// 	this.$store.commit('JIA',this.n)
			// },
			// decrement(){
			// 	this.$store.commit('JIAN',this.n)
			// },


			//借助mapMutations生成对应的方法,方法中会调用commit去联系mutaions
			...mapMutations({increment:'JIA',decrement:'JIAN'}),

使用之后的整个代码

main.js和App.vue时不变的

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, //当前的和 
    school:'尚硅谷',
    subject:'前端'
}

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


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


count.vue

<template>
	<div>
		<h1>当前求和为:{{sum}}</h1>
		<h3>当前求和放大10倍为:{{bigSum}}</h3>
		<h3>我在{{school}} 学习{{subject}}</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(n)">+</button>
		<button @click="decrement(n)">-</button>
		<button @click="incrementOdd(n)">当前求和为奇数再加</button>
		<button @click="incrementWait(n)">等一等再加</button>
	</div>
</template>

<script>
    import {mapActions, mapGetters, mapMutations, mapState} from 'vuex'
	export default {
		name:'Count',
		data() {
			return {
				n:1, //用户选择的数字
				
			}
		},
		computed:{
			// sum(){
			// 	return this.$store.state.sum
			// },
			// school(){
			// 	return this.$store.state.school
			// },
			// subject(){
			// 	return this.$store.state.subject
			// },
			// bigSum(){
			// 	return this.$store.getters.bigSum
			// },

			//借助mapState生成计算属性,从state读取数据(对象写法)
			//  ...mapState({he:'sum',xuexiao:'school',xueke:'subject'})

			//借助mapState生成计算属性,从state中读取数据(数组写法)
			 ...mapState(['sum','school','subject']),

			 ...mapGetters(['bigSum'])



		},
		methods: {
			// increment(){
			// 	this.$store.commit('JIA',this.n)
			// },
			// decrement(){
			// 	this.$store.commit('JIAN',this.n)
			// },


			//借助mapMutations生成对应的方法,方法中会调用commit去联系mutaions
			...mapMutations({increment:'JIA',decrement:'JIAN'}),


			// incrementOdd(){
			// 		this.$store.dispatch('jiaOdd',this.n)
			// },
			// incrementWait(){
			// 		this.$store.dispatch('jiaWait',this.n)	
			// },

			//
			...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})

		},
		mounted(){
			const x =mapState({he:'sum',xuexiao:'school',xueke:'subject'})
			console.log(x)
		}
	}
</script>

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

多组件共享数据

即以index.js中的属性为公共汽车。来通过调用其中的属性来实现一个数据间的共享

index.js(这个区域主要是添加了增加人员的方法,在mutations处)

//该文件用于创建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
    },
    ADD_PERSON(state,value){
        console.log('mutations中的ADD_PERSON被调用勒')
        state.personList.unshift(value)
    }
   
}

//准备state -用于存储数据
const state ={
    sum:0, //当前的和 
    school:'尚硅谷',
    subject:'前端',
    personList:[
        {id:'001',name:'张三'}
    ]
}

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


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


Person.vue

<template>
  <div>
    <h1>人员列表</h1>
    <h3 style="color:blue">上方组件的求和为{{sum}}</h3>
    <input type="text" placeholder="请输入名字" v-model="name">
    <button @click="add">添加</button>
    <ul>
        <li v-for="p in personList" :key="p.id">{{p.name}}</li>
        
    </ul>
        
  </div>
</template>

<script>
import { nanoid } from 'nanoid'

export default {
    name:'Person',
    data(){
        return{
            name:''
        }
    },
    computed:{
        personList(){
            return this.$store.state.personList
        },
        sum(){
            return this.$store.state.sum
        }
    },
    methods:{
        add(){
            const personObj={id:nanoid(),name:this.name}
            this.$store.commit('ADD_PERSON',personObj)
            this.name=''
            
        }
    }
}
</script>

count.vue(这里主要是在mapstate属性中添加我要获取的personList,然后在展示处展示)

<template>
	<div>
		<h1>当前求和为:{{sum}}</h1>
		<h3>当前求和放大10倍为:{{bigSum}}</h3>
		<h3>我在{{school}} 学习{{subject}}</h3>
		<h3 style="color:red">下方组件的总人数是:{{personList.length}}</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(n)">+</button>
		<button @click="decrement(n)">-</button>
		<button @click="incrementOdd(n)">当前求和为奇数再加</button>
		<button @click="incrementWait(n)">等一等再加</button>
	</div>
</template>

<script>
    import {mapActions, mapGetters, mapMutations, mapState} from 'vuex'
	export default {
		name:'Count',
		data() {
			return {
				n:1, //用户选择的数字
				
			}
		},
		computed:{
			// sum(){
			// 	return this.$store.state.sum
			// },
			// school(){
			// 	return this.$store.state.school
			// },
			// subject(){
			// 	return this.$store.state.subject
			// },
			// bigSum(){
			// 	return this.$store.getters.bigSum
			// },

			//借助mapState生成计算属性,从state读取数据(对象写法)
			//  ...mapState({he:'sum',xuexiao:'school',xueke:'subject'})

			//借助mapState生成计算属性,从state中读取数据(数组写法)
			 ...mapState(['sum','school','subject','personList']),

			 ...mapGetters(['bigSum'])



		},
		methods: {
			// increment(){
			// 	this.$store.commit('JIA',this.n)
			// },
			// decrement(){
			// 	this.$store.commit('JIAN',this.n)
			// },


			//借助mapMutations生成对应的方法,方法中会调用commit去联系mutaions
			...mapMutations({increment:'JIA',decrement:'JIAN'}),


			// incrementOdd(){
			// 		this.$store.dispatch('jiaOdd',this.n)
			// },
			// incrementWait(){
			// 		this.$store.dispatch('jiaWait',this.n)	
			// },

			//
			...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})

		},
		mounted(){
			const x =mapState({he:'sum',xuexiao:'school',xueke:'subject'})
			console.log(x)
		}
	}
</script>

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

下面是一个使用Java Stream进行分组求和的例子: ```java import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class GroupingAndSummingExample { public static void main(String[] args) { // 创建一个包含多个学生的列表 List<Student> students = Arrays.asList( new Student("Alice", "Math", 85), new Student("Bob", "English", 75), new Student("Alice", "English", 90), new Student("Bob", "Math", 80), new Student("Charlie", "Math", 95) ); // 使用Stream进行分组求和 Map<String, Integer> sumByStudent = students.stream() .collect(Collectors.groupingBy(Student::getName, Collectors.summingInt(Student::getScore))); // 打印每个学生的总分 sumByStudent.forEach((name, totalScore) -> System.out.println(name + ": " + totalScore)); } static class Student { private String name; private String subject; private int score; public Student(String name, String subject, int score) { this.name = name; this.subject = subject; this.score = score; } public String getName() { return name; } public String getSubject() { return subject; } public int getScore() { return score; } } } ``` 上述例子中,我们创建了一个包含多个学生的列表。然后使用Stream的`groupingBy`方法对学生进行分组,按照学生名字进行分组,并通过`summingInt`方法对每个分组中的学生成绩进行求和。最后,我们遍历结果Map,打印每个学生的总分。 运行上述代码,将会输出: ``` Alice: 175 Bob: 155 Charlie: 95 ``` 可以看到,学生Alice的总分是175,学生Bob的总分是155,学生Charlie的总分是95。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值