import store from "./store"
computed: {
useName: function() {
return store.state.userName
}
}
mapState 函数返回的是一个对象。我们如何将它与局部计算属性混合使用呢?
通常,我们需要使用一个工具函数将多个对象合并为一个,以使我们可以将最终对象传给 computed 属性。但是自从有了对象展开运算符(现处于 ECMASCript 提案 stage-3 阶段),我们可以极大地简化写法:
computed: {
// 使用对象展开运算符将此对象混入到外部对象中
....mapState({
useName: state => state.useName
}),
还可以按照如下方式使用mapState辅助函数:
在index.js文件中:
import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'
import actions from './action'
import getters from './getters'
Vue.use(Vuex)
const state = {
userInfo: { phone: 111 }, //用户信息
orderList: [{ orderno: '1111' }], //订单列表
orderDetail: null, //订单产品详情
login: false, //是否登录
}
export default new Vuex.Store({
state,
getters,
actions,
mutations,
})
在需要使用store中的各个状态变量的自定义的vue组件中:
computed: {
...mapState([
'orderList',
'login'
]),
},
mounted(){
console.log(typeof orderList); ==>undefind
console.log(typeof this.orderList)==>object
}
mapState通过扩展运算符将store.state.orderList 映射this.orderList 这个this 很重要,这个映射直接映射到当前Vue的this对象上。
所以通过this都能将这些对象点出来,同理,mapActions, mapMutations都是一样的道理。牢记~~~
参考链接:mapState使用