Mrcdh技术博客 Mrcdh技术博客
首页
  • Html5
  • Javascript
  • Nodejs
  • electron
  • Android
  • 微信公众号
  • 框架
  • 其他
  • Mysql
  • PHP
  • Python
  • java
  • Gulp
  • 其它
  • 网站
  • 资源
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

Mrcdh

全栈开发小学生
首页
  • Html5
  • Javascript
  • Nodejs
  • electron
  • Android
  • 微信公众号
  • 框架
  • 其他
  • Mysql
  • PHP
  • Python
  • java
  • Gulp
  • 其它
  • 网站
  • 资源
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • Nuxt配置实现axios在开发时的跨域代理
  • Token的设置与存储
  • Nuxt的API 封装及解耦
    • 创建 api 模块
    • 创建 api 插件
    • 配置 nuxt.config.js
    • 具体使用
      • asyncData 中
      • 页面中
      • store 中
    • 注意
  • nuxt常见问题
  • 《Nuxtjs》
mrcdh
2021-04-03
目录

Nuxt的API 封装及解耦

# 创建 api 模块

|--api
    |---index.js       // api模块入口文件
    |---apilist
        |---home.js    // 各个api接口
        |---article.js
1
2
3
4
5

api/index.js用于导入apilist中的所有接口,此时api/index模块导出为一个object, 参数为apilist中每个文件名,value值为对应的函数

// api/index.js
const modulesFiles = require.context("./apilist", true, /\.js$/);
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, "$1");

  const value = modulesFiles(modulePath);

  modules[moduleName] = value.default || value;

  return modules;
}, {});

export default modules;
1
2
3
4
5
6
7
8
9
10
11
12
13
//home.js 传入的axios参数调用
export default (axios) => ({
  list(data) {
    return axios.post(`/api/home/list`, data);
  },
});
1
2
3
4
5
6

# 创建 api 插件

使用plugin中inject参数暴露api ,api注入到服务端context, vue实例, vuex中。

//plugins/api-plugin.js

import apis from "@/api/index";
export default (ctx, inject) => {
  var apiObject = {};
  for (var i in apis) {
    apiObject[i] = apis[i](ctx.$axios);
  }

  //文档: https://www.nuxtjs.cn/guide/plugins
  //inject:注入到服务端context, vue实例, vuex中
  inject("api", apiObject);
};
1
2
3
4
5
6
7
8
9
10
11
12
13

# 配置 nuxt.config.js

plugins: ["@/plugins/axios", "@/plugins/api-plugins"]
1

# 具体使用

# asyncData 中

asyncData(ctx){
    return ctx.app.$api.home.list({page: 99}).then(res=>{
        return {
            data: res.data
        }
    })
}
1
2
3
4
5
6
7

# 页面中

mounted(){
    this.$api.home.list({page: 99}).then(res=>{
        this.data=res.data
    })
}
1
2
3
4
5

# store 中

export const actions = {
  GET_LIST({ commit }) {
    return this.$api.home.list({ page: 99 }).then((res) => {
      commit("setlist", res.data);
    });
  },
};
1
2
3
4
5
6
7

# 注意

  • asyncData 需返回 Promise,Promise 中返回当前页面所需的数据, 或者使用 callback 回调出所需的数据, 或者使用 async await, 具体[参考文档 https://www.nuxtjs.cn/guide/async-data]
  • nuxt 安装时勾选"@nuxtjs/axios"插件
#Nuxtjs
上次更新: 2024/02/22, 14:16:55
Token的设置与存储
nuxt常见问题

← Token的设置与存储 nuxt常见问题→

最近更新
01
uniapp常见问题
03-19
02
Vue3项目搭建
12-25
03
使用pnpm的monorepo组织项目
11-01
更多文章>
Theme by Vdoing | Copyright © 2020-2025 Mrcdh | 苏ICP备2020058908号-1
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式
×