【问题标题】:How to pass data from vuex store through module to vue component?如何通过模块将数据从 vuex 存储传递到 vue 组件?
【发布时间】:2019-11-29 07:48:24
【问题描述】:

我可以控制数据,也可以在 vuex 开发工具中查看数据 但无法在表格中显示它们。请如果有人可以检查 我的代码并告诉我它有什么问题。谢谢各位。我尝试了不同的方法,例如 async/await、promise、getters……但我无法获取数据,可能是我没有正确调用它。

ROLE.VUE

<emplate>
  <di>
    <p v-for="(role, index) in roles :key="index">
  </div>
</template>

<script>

import { mapState } from 'vuex'

export default ({
  name: 'Role',
  metaInfo: {
    title: 'Role'
  },

  created  () {
    this.$store.dispatch('loadRoles').then((response) => { console.log(response) })
  },

  computed: {
    ...mapState([
      'roles'
    ])
  }
})

</script>

role.js

import Axios from 'axios'

export default {
//   namespaced: true,

  state: {
    roles: [],
  },

  getters: {
    roles (state) {
      return state.roles
    }
  },

  mutations: {
    SET_ROLES (state, roles) {
      state.roles = roles
    }
  },

  actions: {

loadRoles ({ commit }) {
  Axios.get('/settings/roles')
    .then((response) => {
      console.log(response.data)
      //   let roles = response.data
      commit('SET_ROLES', response.data.roles)
    })
}

} }

index.js

import role from './role'

Vue.use(Vuex)

export const store = new Vuex.Store({
  state: {

  },

  mutations: {
    //
  },

  modules: {
    role
  },

  actions: {
    //
  }
})

Main.js

import { store } from './store/store'
new Vue({
router,
store,
ValidationProvider,
render: h => h(App)
})

【问题讨论】:

    标签: javascript vue.js vuejs2 vuex vuex-modules


    【解决方案1】:

    从带有mapState 的模块加载时,您需要指定要从中加载的模块的名称。以下是您的案例的正确语法:

    ...mapState('role', ['roles'])
    

    第一个参数是模块名称,第二个参数是来自该模块的state 属性数组。

    【讨论】:

    • 我收到了这个错误。 [vuex] 未知动作类型:loadRoles vuex.esm.js:419。创建钩子时出错:“TypeError: this.$store.dispatch(...) is undefined”
    • 这将与任何映射无关,这是您尝试通过 Vue 实例属性访问商店的错误。该错误的原因也是语法。应该是this.$store.dispatch('role/loadRoles')。你可以参考文档来学习使用 vuex 模块的语法。
    • 错误信息消失了,但数据仍然没有显示在 vue 组件中
    • 你没有做任何事情来展示它。这也是错误的语法:&lt;p v-for="(role, index) in roles :key="index"&gt;。您没有关闭v-for 的引号,即使那样,它也只会创建p 元素并设置一个键,但实际上并没有尝试显示任何数据。你需要像&lt;p v-for="(role, index) in roles" :key="index"&gt;{{ role }}&lt;/p&gt; 这样的东西。如果你是 Vue 的新手,我会先尝试一些教程。
    • ,你是完全正确的。我在对代码进行故障排除时评论了这一行。
      让角色 = response.data, commit('SET_ROLES', roles)。它现在按预期工作。非常感谢
    猜你喜欢
    • 2021-01-20
    • 2018-10-02
    • 2018-09-04
    • 2020-09-05
    • 2017-07-02
    • 1970-01-01
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多