我正在配置 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 许可协议
据我所知,您只能在商店的操作下访问 nuxtServerInit() 中的 axios,就像这样
查看此页面 https://axios.nuxtjs.org/usage 以获取有关如何在 NuxtJS 项目中使用 axios 的更多信息。