Vuex入门(2)—— state,mapState,...mapState对象展开符详解
买泛域名SSL证书 送5斤装现摘猕猴桃一箱、同时提供技开源商城搭建免费技术支持。
泛域名ssl证书 239元1年送1个月、单域名39元1年,Sectigo(原Comodo证书)全球可信证书,强大的兼容性,高度安全性,如有问题7天内可退、可开发票
加微信VX 18718058521 备注SSL证书
【腾讯云】2核2G4M云服务器新老同享99元/年,续费同价
2.
泛域名ssl证书 239元1年送1个月、单域名39元1年,Sectigo(原Comodo证书)全球可信证书,强大的兼容性,高度安全性,如有问题7天内可退、可开发票
加微信VX 18718058521 备注SSL证书
【腾讯云】2核2G4M云服务器新老同享99元/年,续费同价
1.state
//state.js
let state = {
count: 1,
name: 'dkr',
sex: '男',
from: 'china'
}
export default state<template>
<div id="example">
<button @click="decrement">-</button>
{{count}}
{{dataCount}}
<button @click="increment">+</button>
</div>
</template>
<script>
export default {
data () {
return {
dataCount: this.$store.state.count //用data接收
}
},
computed:{
count(){
return this.$store.state.count //用computed接收
}
}
methods: {
increment () {
this.$store.commit('increment')
},
decrement () {
this.$store.commit('decrement')
}
}
}
</script>2.mapState 辅助函数
import { mapState } from 'vuex'<template>
<div id="example">
<button @click="decrement">-</button>
{{count}}
{{dataCount}}
<button @click="increment">+</button>
<div>{{sex}}</div>
<div>{{from}}</div>
<div>{{myCmpted}}</div>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
data () {
return {
str: '国籍',
dataCount: this.$store.state.count
}
},
computed: mapState({
count: 'count', // 第一种写法
sex: (state) => state.sex, // 第二种写法
from: function (state) { // 用普通函数this指向vue实例,要注意
return this.str + ':' + state.from
},
// 注意下面的写法看起来和上面相同,事实上箭头函数的this指针并没有指向vue实例,因此不要滥用箭头函数
// from: (state) => this.str + ':' + state.from
myCmpted: function () {
// 这里不需要state,测试一下computed的原有用法
return '测试' + this.str
}
}),
methods: {
increment () {
this.$store.commit('increment')
},
decrement () {
this.$store.commit('decrement')
}
},
created () {
// 写个定时器,发现computed依旧保持了只要内部有相关属性发生改变不管是当前实例data中的改变,还是vuex中的值改变都会触发dom和值更新
setTimeout(() => {
this.str = '国家'
}, 1000)
}
}
</script>//之前的computed
computed:{
fn1(){ return ...},
fn2(){ return ...},
fn3(){ return ...}
........
}
//引入mapState辅助函数之后
computed:mapState({
//先复制粘贴
fn1(){ return ...},
fn2(){ return ...},
fn3(){ return ...}
......
//再维护vuex
count:'count'
.......
})3 ...mapState
然后来看一个例子.
let MapState = mapState({
count: 'count',
sex: (state) => state.sex
})
let json = {
'a': '我是json自带的',
...MapState
}
console.log(json)//之前的computed
computed:{
fn1(){ return ...},
fn2(){ return ...},
fn3(){ return ...}
........
}
//引入mapState辅助函数之后
computed:{
//原来的继续保留
fn1(){ return ...},
fn2(){ return ...},
fn3(){ return ...}
......
//再维护vuex
...mapState({ //这里的...不是省略号了,是对象扩展符
count:'count'
})
}


