xKx*_*xKx 5 javascript vue.js axios vuex nuxt.js
我正在按如下方式配置 Nuxt.js 的 VUEX。
store
??? README.md
??? posts
? ??? actions.js
? ??? getters.js
? ??? index.js
? ??? mutations.js
? ??? utils
? ??? getPostById.js
??? index.js
Run Code Online (Sandbox Code Playgroud)
我@nuxtjs/axios在 nuxt.config.js 中添加了模块并使其可以this.$axios.$get在操作中使用。
但是,您不能在 store/posts/utils/getPostById.js 中使用 A。会发生
错误Cannot read property '$axios' of undefined。
每个代码描述如下。
? 商店/index.js
import Vuex from 'vuex'
import postsModule from './posts'
new Vuex.Store({
modules: {
posts: postsModule
}
})
Run Code Online (Sandbox Code Playgroud)
?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
}
Run Code Online (Sandbox Code Playgroud)
? 商店/帖子/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)
}
}
Run Code Online (Sandbox Code Playgroud)
? 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
}
Run Code Online (Sandbox Code Playgroud)
我如何this.$axios.$get在里面使用getPostById.js?
Cri*_*ara 10
自从发布问题以来,很多事情都发生了变化。您现在可以$axios通过访问商店中的实用程序this.$axios。插件使用nuxtinject使$axios所描述的在商店可用对象这里。
举个例子:
export const actions = {
async fetchUser () {
let user = await this.$axios.$get('/me');
}
}
Run Code Online (Sandbox Code Playgroud)
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)
}
Run Code Online (Sandbox Code Playgroud)
Check this page https://axios.nuxtjs.org/usage for more information on how to use axios in NuxtJS projects.
| 归档时间: |
|
| 查看次数: |
11391 次 |
| 最近记录: |