vue 狀態管理 三、Mutations和Getters用法
阿新 • • 發佈:2022-01-29
系列導航
vue 狀態管理 三、Mutations和Getters用法
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>