在option API 中使用mapState
import { mapState } from 'vuex'
export default {
computed: {
...mapState(['name', 'age', 'height'])
}
}
在composition API 中使用mapState
`<template>
<div>
<h2>单个获取name: {{sName}}<h2>
<h2>多个获取name: {{name}}</h2>
</div>
</template>`
import { computed } from 'vue'
import { useStore, mapState } from 'vuex'
exoprt default {
setup() {
const store = useStore();
const sName = computed(() => store.state.name)
const sAge = computed(() => store.state.age)
const sHeight = computed(() => store.state.height)
const storeStateFns = mapState(['name', 'age', 'height'])
const storeState = {}
Object.keys(storeStateFns).forEach(fnKey => {
const fn = storeStateFns[fnKey].bind({$store: store})
storeState[fnKey] = computed(fn)
})
return {
...storeState
}
}
}