一、准备工作
1.安装vuex
npm install vuex --save
2.创建vuex
import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'
import actions from './actions'
import getters from './getters'
Vue.use(Vuex)
const state = {
cartList: []
}
const store = new Vuex.Store({
state,
mutations,
actions,
getters
})
export default store
3.注入(main.js)
可通过this.$store 使用
new Vue({
el: '#app',
store
})
二、state
取数据
this.$store.state.count
辅助函数:mapState
1.数组形式
映射的计算属性的名称与 state 的子节点名称相同
import {mapState} from 'vuex'
export default {
name: 'home',
computed: mapState(['username','age'])
}
//相当于
computed:{
username(){return this.$store.state.username},
age(){return this.$store.state.age},
}
2.对象形式
对象形式可以自定义计算属性名称
import { mapState } from 'vuex'
export default {
computed:mapState({
count: 'count',//state中的count
name: (state) => state.name,//state中的name
// 为了能够使用 `this` 获取局部状态,必须使用常规函数
countPlusLocalState (state) {
return state.count + this.localCount //返回经过处理的count
},
getMore(state){
return 'more'+state.name;//返回处理过的name
},
localComputed(){
return '我是局部计算属性';//局部计算属性
}
})
console.log(this.count);
console.log(this.name);
console.log(this.getMore);
console.log(this.localComputed);

理解countPlusLocalState和getMore:本来是直接取得state中定义的数据(count和name),但是有时候也需要把数据做处理后再使用。所以可以自定义一个计算属性名,然后在mapState中取得state对象,把通过state取到的数据做进一步处理后再赋值给计算属性。这样就可以直接用this.getMore和this.localComputed来调用经过处理的数据了。
理解 localComputed:如果该组件有自己的计算属性,也可以写在mapState中,最后也会被映射到计算属性中。即既能映射取到state属性值的函数,也能映射普通函数。但是不推荐这种写法,而是使用对象展开运算符,将mapState中的属性混入到computed中。(如下面第三点展示)
注意如果要取组件实例的数据,就不能使用箭头函数,箭头函数中this并不是指向vue组件实例
3.与局部计算属性混合使用
对象
computed: {
localComputed () {},
// 使用对象展开运算符将此对象混入到外部对象中
...mapState({
// ...
})
}
数组
computed: {
getValue(){
return this.val/7
},
...mapState(['username','age'])
}
补充
对象展开运算符
let MapState = mapState({
count: 'count',
sex: (state) => state.sex
})
let json = {
'a': '我是json自带的',
...MapState
}
console.log(json)

网友评论