之前介绍nuxt 的根本用法,当初须要与后端联调,为了方便使用,于是进行接口的封装。

一,axios

1,装置
npm install @nuxtjs/axios
2,配置axios

// nuxt.config.jsmodules: [  '@nuxtjs/axios',  '@nuxt/content'],axios: {  baseURL: process.env.BASE_URL,},

3,封装接口

export default function ({ app, $axios},inject) {  const API = {};  // 我本人这么写,会呈现 Maximum call stack size exceeded 的问题。  // API.getGameList = function () {  //   return $axios({  //     url: '/apps.json',  //     method: 'get',  //   })  // };  API.getGameList = function () {    return $axios.$get('/apps.json')  };  // 应用 inject 之后,能够通过 this.$api.getGameList 调用接口  app.api = API;  inject('api',API);}

4.1,asyncData 调用接口

async asyncData(context) {  const apiGame = await context.app.api.getGameList();  await console.log('获取接口', process.env.BASE_URL, apiGame)  return { apiGame }},

4.2,methods 里应用

methods: {  async handleGame(){    console.log('$api---',this.$api)    const tempGame = await this.$api.getGameList();    console.log('tempGame',tempGame)  }}

二,环境变量

nuxt 的环境变量是配在 package.json 文件里的
1,装置cross-env
npm i cross-env -D
2,批改 package.json 文件中的 scripts

 "scripts": {    "dev": "cross-env BASE_URL=http://192.168.XXX.XXX:8080 NODE_ENV=development nuxt",    "build": "nuxt build",    "start": "nuxt start",    "generate": "nuxt generate",    "release": "nuxt generate",    "lint:js": "eslint --ext \".js,.vue\" --ignore-path .gitignore .",    "lint": "yarn lint:js"  },

3,在nuxt.config.js 增加配置

env: {  BASE_URL: process.env.BASE_URL,  NODE_ENV: process.env.NODE_ENV},

配置实现之后,须要重启一下服务,能力获取到 BASE_URL