发布于 4年前

如何在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 to modulesnuxt.config.js模块中,并使其 this.$axios.$get 可以使用。

但是却不能在store/posts/utils/getPostById.js中使用,会报错 Cannot read property '$axios' of undefined will occur

相关代码片段如下: ・ 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
}

我如何在this.$axios.$get内部使用getPostById.js

解决方案:

据我所知,您只能在 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的更多信息。

©2020 edoou.com   京ICP备16001874号-3