I am configuring VUEX of Nuxt.js as follows.
store
├── README.md
├── posts
│ ├── actions.js
│ ├── getters.js
│ ├── index.js
│ ├── mutations.js
│ └── utils
│ └── getPostById.js
└── index.js
I added @nuxtjs/axios
to modules in nuxt.config.js and make it possible to use this.$axios.$get
in actions.
However, you can not use A in store/posts/utils/getPostById.js.
An error of Cannot read property '$axios' of undefined
will occur.
Each code is described as follows.
・ 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
}
How can I use this.$axios.$get
inside getPostById.js
?
Quite a few things have changed since the question was posted. You can now access the $axios
utility in the store via this.$axios
. The nuxt plugin uses inject
to make the $axios
object available in the store as described here.
As an example:
export const actions = {
async fetchUser () {
let user = await this.$axios.$get('/me');
}
}
To the best of my knowledge, you can only access axios in your nuxtServerInit() under actions in your store like so
async nuxtServerInit ({ commit }, { $axios }) {
const ip = await $axios.$get('http://icanhazip.com')
commit('SET_IP', ip)
}
Check this page https://axios.nuxtjs.org/usage for more information on how to use axios in NuxtJS projects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With