原始写法
<template>
<div>
<h1>当前求和为: {{ sum }}</h1>
<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: 'Category',
data() {
return {
n: 1,
sum: 0
}
},
methods: {
increment() {
this.sum += this.n;
},
decrement() {
this.sum -= this.n;
},
incrementOdd() {
if (this.sum % 2) {
this.sum += this.n;
}
},
incrementWait() {
setTimeout(() => {
this.sum += this.n;
}, 500)
},
},
}
</script>
Vuex写法
<script>
import {mapGetters, mapState,mapMutations,mapActions} from 'vuex'
export default {
name: 'Category',
data() {
return {
n: 1,
}
},
computed: {
// 此处方法相当于上面方法,从state中取数据 对象写法
// ...mapState({sum:'sum',school:'school',subject:'subject'}),
// 数组写法,需要计算属性和his.$store.state.sum中sum 名字相同
...mapState('countOption',['sum','school','subject']),
...mapState('personOption',['personList']),
// 对象写法
// ...mapGetters({addAll:'addAll'}),
// 数组写法
...mapGetters('countOption',['addAll'])
},
methods: {
// 在mapMutations中生成对应方法,方法中会调用commit去调用$mutation 对象写法
...mapMutations('countOption',{increment:'ADDM',decrement:'ADDL'}),
// 对象写法 参数要在调用端添加
...mapActions('countOption',{incrementOdd:'addLM',incrementWait:'addLMW'})
},
mounted() {
},
}
引入Vuex
main.js
// 引入store 如果填写的是vue可以认识的名称可以忽略不写
import store from './store/index'
标签:...,countOption,VueX,sum,mapState,写法,对比,store
From: https://www.cnblogs.com/aljyailianjiayou/p/17701763.html