javascript - `$axios`在Nuxt.js的Vuex实用函数中的使用方法

标签 javascript vue.js axios vuex nuxt.js

我正在配置Nuxt.js的VUEX如下。

store
├── README.md
├── posts
│   ├── actions.js
│   ├── getters.js
│   ├── index.js
│   ├── mutations.js
│   └── utils
│       └── getPostById.js
└── index.js

我将 @nuxtjs/axios 添加到 nuxt.config.js 中的模块,并使其可以在操作中使用 this.$axios.$get
但是,您不能在 store/posts/utils/getPostById.js 中使用 A。
会出现Cannot read property '$axios' of undefined的错误。

各代码说明如下。

・ store/index.js

import Vuex from 'vuex'
import postsModule from './posts'

new Vuex.Store({
  modules: {
    posts: postsModule
  }
})

・store/posts/index.js

import actions from './actions'
import getters from './getters'
import mutations from './mutations'

export const state = () => ({
  posts: [],
  post: {}
})

export default {
  namespaced: true,
  state,
  actions,
  getters,
  mutations
}

・ store/posts/actions.js

import getPostById from './utils/getPostById'

export default {
  async fetchPost({ commit }, count = 10) {
    const params = { count: count }
    // Here `$axios` can be used normally
    const result = await this.$axios.$get("ApiUrl")
    commit('setPosts', result)
  },
  async fetchPostById({ commit }, category_ids, count = 10) {
    const topCommunities = {}
    const result = await getPostById(id)
    commit('setPost', result)
  }
}

・ store/posts/utils/getPostById.js

export default async function(post_id) {
  // Here `$axios` can not use
  const result = await this.$axios.$get(`${ApiUrl}/${post_id}`)
  return result
}

如何在 getPostById.js 中使用 this.$axios.$get

最佳答案

自问题发布以来,有不少事情发生了变化。您现在可以通过 this.$axios 访问商店中的 $axios 实用程序。 nuxt 插件使用 inject 使 $axios 对象在商店中可用,如所述 here .

举个例子:

export const actions = {
    async fetchUser () {
        let user = await this.$axios.$get('/me');
    }
}

关于javascript - `$axios`在Nuxt.js的Vuex实用函数中的使用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54570522/

相关文章:

javascript - ReactJS Axios 它不允许我将数组分配为属性

javascript - 使用数组中的值初始化 Vuex 参数

vue.js - vue js项目中的动态站点地图生成器

node.js - CORS 问题,HapiJS HAPI-16

javascript - 如何解决这个javascript函数

javascript - foreach - 显示数据的正确行和列

javascript - Vue.js 关于 html 渲染的指令

reactjs - 为什么我的 get 路由不运行我的 Mongoose 查询?

node.js - 使用流下载大文件时的 Axios 事件

javascript - 通过 Angular 下载文件