如何在 Nuxt.js 的 Vuex 实用函数中使用 \`$axios\`

新手上路,请多包涵

我正在配置 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
  }
})

・商店/帖子/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
}

・ 商店/帖子/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
}

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

原文由 xKxAxKx 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 571
2 个回答

据我所知,您只能在商店的操作下访问 nuxtServerInit() 中的 axios,就像这样

async nuxtServerInit ({ commit }, { $axios }) {
  const ip = await $axios.$get('http://icanhazip.com')
  commit('SET_IP', ip)
}

查看此页面 https://axios.nuxtjs.org/usage 以获取有关如何在 NuxtJS 项目中使用 axios 的更多信息。

原文由 Jalasem 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

举个例子:

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

原文由 Cristian Calara 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题