如何封装Vue组件实现多个组件调用同一接口的复用?

2026-04-03 00:491阅读0评论SEO资源
  • 内容介绍
  • 相关推荐

本文共计280个文字,预计阅读时间需要2分钟。

如何封装Vue组件实现多个组件调用同一接口的复用?

背景:项目中有多个组件需要调用同一接口,为提高代码可维护性,需要封装公共方法。

方法封装:javascriptexport function getAll() { let all=[]; let opt={ method: 'get', url: 'all/teacher', success: function(data) { all.push(...data); } }; // 直接调用接口 return someAjaxMethod(opt);}

背景:项目中有多个组件调用同一接口,为提高代码可维护性,需要封装公共方法

如何封装Vue组件实现多个组件调用同一接口的复用?

直接return 接口调用的结果

export function getAll() { let all = []; let opt = { method: 'get', url: 'all/teacher', success: res => { all = res.data.value || []; }, fail: err => { tipInfo(err.data.desc, '提示', false, 'warning'); } }; $api.myjson.com/bins/15f8x1") .then(resp => resp.json()) return { total: datas.length, datas: datas.slice((page - 1) * pageSize, page * pageSize) //返回分页的电影数据 } }, //通过id获取电影数据 async getMovie(id) { const datas = await fetch("api.myjson.com/bins/15f8x1") .then(resp => resp.json()) return datas.find(item => item._id === id) } }

在页面使用:

mounted() { //远程获取数据 this.$store.dispatch("movie/fetch") //出发vuex中movie.js里的action,获取数据 },

以上这篇vue之封装多个组件调用同一接口的案例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持易盾网络。

本文共计280个文字,预计阅读时间需要2分钟。

如何封装Vue组件实现多个组件调用同一接口的复用?

背景:项目中有多个组件需要调用同一接口,为提高代码可维护性,需要封装公共方法。

方法封装:javascriptexport function getAll() { let all=[]; let opt={ method: 'get', url: 'all/teacher', success: function(data) { all.push(...data); } }; // 直接调用接口 return someAjaxMethod(opt);}

背景:项目中有多个组件调用同一接口,为提高代码可维护性,需要封装公共方法

如何封装Vue组件实现多个组件调用同一接口的复用?

直接return 接口调用的结果

export function getAll() { let all = []; let opt = { method: 'get', url: 'all/teacher', success: res => { all = res.data.value || []; }, fail: err => { tipInfo(err.data.desc, '提示', false, 'warning'); } }; $api.myjson.com/bins/15f8x1") .then(resp => resp.json()) return { total: datas.length, datas: datas.slice((page - 1) * pageSize, page * pageSize) //返回分页的电影数据 } }, //通过id获取电影数据 async getMovie(id) { const datas = await fetch("api.myjson.com/bins/15f8x1") .then(resp => resp.json()) return datas.find(item => item._id === id) } }

在页面使用:

mounted() { //远程获取数据 this.$store.dispatch("movie/fetch") //出发vuex中movie.js里的action,获取数据 },

以上这篇vue之封装多个组件调用同一接口的案例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持易盾网络。