如何在组件里面使用这些来自Vuex的数据?

问题描述 投票:0回答:1

在需要的组件中使用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来绑定该组件中的数据?

vue.js vuejs2 vue-component vuex
1个回答
1
投票

使用 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

© www.soinside.com 2019 - 2024. All rights reserved.