其他分享
首页 > 其他分享> > vue 状态管理 三、Mutations和Getters用法

vue 状态管理 三、Mutations和Getters用法

作者:互联网

系列导航

vue 状态管理 一、状态管理概念和基本结构

vue 状态管理 二、状态管理的基本使用

vue 状态管理 三、Mutations和Getters用法

vue 状态管理 四、Action用法

vue 状态管理 五、Module用法

mutations和getters用法

一、 效果

 

 

 

 

二、 目录结构

 

 

 

三、源码

index.js

import {createStore} from 'vuex'
 

export default createStore({
	state: {
		counter: 0,
		students: [
		  {id: 110, name: 'why', age: 18},
		  {id: 111, name: 'kobe', age: 24},
		  {id: 112, name: 'james', age: 30},
		  {id: 113, name: 'curry', age: 10}
		],
		info: {
		  name: 'kobe',
		  age: 40,
		  height: 1.98
		}
	},
	mutations: {
		increament(state) {
			state.counter++
		},
		decrement(state) {
			state.counter--
		},
		incrementCount(state, payload) {
		  state.counter += payload.count
		},
		addStudent(state, stu) {
		  state.students.push(stu)
		},
		updateInfo(state) {
		  state.info.name = 'coderwhy'
		}
	},
	getters:{
		powerCounter(state) {
		  return state.counter * state.counter
		},
		more20stu(state) {
		  return state.students.filter(s => s.age > 20)
		},
		more20stuLength(state, getters) {
		  return getters.more20stu.length
		} ,
        moreAgeStu(state) {
		// return function (age) {
		//   return state.students.filter(s => s.age > age)
		// }
		return age => {
			return state.students.filter(s => s.age > age)
		}
  }
	},
	actions: {},
	modules: {}
})

 

App.vue

<template>
	<div >
		<h2>-------mutations 的用法----------</h2>
		<h2>{{$store.state.counter}}</h2>
		<button @click="addition">增加+</button>
		<button @click="subtraction">减少-</button>
		<button @click="addCount(5)">+5</button>
		<button @click="addStudent">添加学生</button>
 
		<h2>---------- getters的用法----------</h2>
		<h2>{{$store.getters.powerCounter}}</h2>
		<h2>{{$store.getters.more20stu}}</h2>
		<h2>{{$store.getters.more20stuLength}}</h2>
		<h2>{{$store.getters.moreAgeStu(12)}}</h2>
	</div>
</template>

<script>
	import { 	computed } from 'vue'
	import { 	useStore } from 'vuex'
    import HelloWorld from '@/components/HelloWorld.vue'
	export default {
		components: {
		    HelloWorld
		},
		methods: {
			addCount(count) {
			  // payload: 负载
			  // 1.普通的提交封装
			  // this.$store.commit('incrementCount', count)
			
			  // 2.特殊的提交封装
			  this.$store.commit({
			    type: 'incrementCount',
			    count
			  })
			},
			addStudent() {
			  const stu = {id: 114, name: 'alan', age: 35}
			  this.$store.commit('addStudent', stu)
			},
			 
		},
		setup() {
			const store = useStore()
 
			let addition=() => {
				store.commit('increament')
			}
			let subtraction=() => {
				store.commit('decrement')
				//this.$store.commit('decrement')
			}
			return {
				addition,
				subtraction
			}
		}
	}
</script>

 

标签:vue,return,age,Getters,Mutations,state,getters,store
来源: https://www.cnblogs.com/yclh/p/15855387.html