Как использовать `$ axios` в служебной функции в Vuex из Nuxt.js - PullRequest
0 голосов
/ 07 февраля 2019

Я настраиваю VUEX для Nuxt.js следующим образом.

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 в действиях.
Однако нельзя использовать A в store / posts / utils / getPostById.js.
Произойдет ошибка 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
}

Как я могу использовать this.$axios.$get внутри getPostById.js?

1 Ответ

0 голосов
/ 17 февраля 2019

Насколько мне известно, вы можете получить доступ к axios только в вашем nuxtServerInit () под действиями в вашем магазине, например, так:

async nuxtServerInit ({ commit }, { $axios }) {
  const ip = await $axios.$get('http://icanhazip.com')
  commit('SET_IP', ip)
}

Проверьте эту страницу https://axios.nuxtjs.org/usage для получения дополнительной информации о том, какиспользовать axios в проектах NuxtJS.

...