【问题标题】:How to get access to store from action in VueJS?如何通过 VueJS 中的操作访问商店?
【发布时间】:2020-10-09 03:15:35
【问题描述】:

我正在使用 VueJS 和 Vuex。我通过这种方式将用户 ID 放入商店: vuex screenshot

我尝试将用户 ID 传递给 fetch,但 vuejs 返回错误

([Vue warn]: Error in created hook: "TypeError: this.$store is 未定义")

import { LOAD_APPOINTMENTS } from './types'

export default {
  loadProducts ({ commit }) {
    var user = this.$store.state.user.userid
    fetch('api/appointments/' + user)
      .then((result) => {
        return result.json()
      })
      .then((appointments) => {
        commit(LOAD_APPOINTMENTS, appointments)
      })
      .catch(er => {
        console.log(er)
      })
  }
}

【问题讨论】:

  • 您如何/在哪里调用loadProducts 以及您提供的脚本的文件位置是什么?是某种.js 文件,它只是导出该函数吗?
  • 我提供的脚本是 action.js,我在 App.Vue 中调用 loadProducts。这样:
  • 此操作是user 模块还是存储根目录的一部分?
  • @Phil 不,我有两个商店模块(用户和产品),模块用户将用户 ID 和用户名加载到 vuex 商店,产品从 api 获取并在 vuex 商店中为该用户加载产品跨度>
  • 那么这个动作在哪个模块中?

标签: vue.js vuex


【解决方案1】:

首先,在vuex 文件中引用存储时:

  1. context.state 而不是 this.$store.state。
  2. context 代表所有 this.$store。所以,context.commit 和 context.dispatch。

其次,loadProducts 需要重写为action per docs。

第三,loadProducts 需要将context 合并为参数:

actions: {
  loadProducts (context) {
    ...
    context.commit(...)
    ...
  }
}

正如@phil 在此线程中提到的,完整查看文档很重要,因为这个单一的答案将帮助您调试问题,但可能会出现更多问题(例如fetch错误、文件结构错误、组件/应用级别错误)。

【讨论】:

  • 我喜欢反馈。如果这个问题有帮助或解决了问题,请点赞和/或接受:)
  • 谢谢!但它不起作用。现在 Vuejs 返回上下文未定义 :(,抱歉是我的第一个 vuejs 应用
  • @feli 我建议你仔细阅读文档~vuex.vuejs.org/guide/actions.html#actions
  • 仅供参考,应该是 loadProducts ({ commit, state }) 或只是 loadProducts (context)
  • 动作通过context 作为它们的第一个参数。这个context 具有属性state 和getters 以及函数commit 和dispatch。它通常使用({ state, getters, commit, dispatch }) 进行解构,只选择需要的属性
猜你喜欢
  • 2020-06-03
  • 1970-01-01
  • 2021-03-18
  • 2020-10-28
  • 2020-04-22
  • 2020-12-12
  • 1970-01-01
  • 2016-07-14
  • 2020-11-15
相关资源
最近更新 更多