
使用计算属性:
<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">+</button>
<button @click="decrement">-</button>
<button @click="incrementOdd">当前求和为奇数再加</button>
<button @click="incrementWait">等一等再加</button>
</div>
</template>
computed:{
sum(){
return this.$store.state.sum
},
school(){
return this.$store.state.school
},
subject(){
return this.$store.state.subject
},
发现了重复了 this.$store.state,如何 进行优化==将变化的内容传入,执行里面的return
mapState:引入的映射状态====生成代码
import {mapState,mapGetters} from 'vuex'
借助mapState生成计算属性,从state中读取数据。
return this.$store.state.subject =等于这个
借助mapState生成计算属性,从state中读取数据。对象写法
he生成计算属性,sum去state中寻找sum
computed:{
//借助mapState生成计算属性,从state中读取数据。(对象写法)
...mapState({he:'sum',xuexiao:'school',xueke:'subject'}),
},
mounted() {//he:'sum'传入的变成函数
const x = mapState({he:'sum',xuexiao:'school',xueke:'subject'})
console.log(x)
},
{a:a}===可以省略变成a 但是{a:'a'}--可以省略为[a]
//借助mapState生成计算属性,从state中读取数据。(数组写法)
...mapState(['sum','school','subject']),
mounted() {
const x = mapState({he:'sum',xuexiao:'school',xueke:'subject'})
console.log(x)
},
还有映射getters上的变成计算属性、需要导入mapGetters
import {mapState,mapGetters} from 'vuex'
//借助mapGetters生成计算属性,从getters中读取数据。(对象写法)
...mapGetters({bigSum:'bigSum'})
//借助mapGetters生成计算属性,从getters中读取数据。(数组写法)
...mapGetters(['bigSum'])
