在需要的组件中使用Vuex商店的Action中的这些数据的最佳方法是什么?
import axios from 'axios'
export default {
namespaced: true,
state: {
items: []
},
actions: {
fetchCategories ({state, commit}) {
return axios.get('/api/v1/categories')
.then(res => {
const categories = res.data
commit('setItems', {resource: 'categories', items: categories}, {root: true})
return state.items
})
}
}
}
组件
export default {
components: {
ThreadCreateModal,
ThreadList
},
data () {
return {
...
}
},
computed: {
...
},
created () {
...
},
methods: {
...
}
</script>
我应该在哪里以及如何使用该Action来绑定该组件中的数据?
使用 mapState
从vuex导入它,然后在computed中调用它。
computed: {
...mapState(['items']), // if you dont use namespace
...mapState("your_module_name", ['items'] ) // if you use namespace
},
然后你可以通过 this.items
然而,你可以直接访问它 this.$store.state.items