如何使用 nuxtjs 和 axios?

伊采贾姆

我正在尝试学习 NuxtJs,我一直在关注文档,但在使用$axios时遇到问题this.$axios我尝试创建一个服务目录来向我的 api 发出请求,以使事情有条理和干净。首先我配置了我的 nuxt.config.js

modules: [
    // https://go.nuxtjs.dev/axios
    '@nuxtjs/axios',
  ],

  // Axios module configuration (https://go.nuxtjs.dev/config-axios)
  axios: {
    baseURL: "http://localhost:8000/api/"
  },
  publicRuntimeConfig: {
    axios: {
      baseURL: 'http://localhost:8000/api/'
    }
  },

然后我创建了我的store文件articles.js

import articlesService from '~/services/articlesService'
export const state = () => ({
    indexArticles: [],
})
export const actions = {
  async fetchArticles ({ commit, dispatch }) {
    try {
      const response = await articlesService.fetchArticles()
      commit('fetchStart')
      commit('setArticles', response.data.results)
      commit('fetchEnd')
      this._vm.$q.loading.hide()
      return response
    } catch (error) {
      commit('setError', error)
      this._vm.$q.loading.hide()
    }
  },
}

articlesServices.js文件:

function fetchIndexArticles () {
  return this.$axios.get('articleslist/index/')
}
export default {
  fetchIndexArticles
}

我尝试过变体:

function fetchIndexArticles ({$axios}) {
  return $axios.get('articleslist/index/')
}

只有一个是有效的,但我所有的请求都将如此相似和硬编码:

import axios from 'axios'
function fetchIndexArticles () {
  return axios.get('http://localhost:8000/api/articleslist/index/')
}

你能告诉我的正确用法axiosNuxtJs谢谢

艾哈迈德巴格维

尝试使用 $

function fetchIndexArticles () {
  return this.$axios.$get('articleslist/index/')
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章