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