建站教程

建站教程

Products

当前位置:首页 > 建站教程 >

vue封装多个方法function在一个文件(vue之封装多个组件调用同一接口的案例)

GG网络技术分享 2025-03-18 16:14 0


vue封装多个方法function在一个文件

要实现的效果:将所有的全局方法都放在common.js文件中,在main.js进行全局注册,在其他vue组件中直接使用。

1、新建一个common.js,内容如下:

//interfaces 是封装的接口地址文件

import interfaces from "./interfaces.js"

const common = {

//nowTime 获取当前时间的时间戳

nowTime: function() {

return Date.parse(new Date()) / 1000;

},

// 登录领取每天奖励

getDayaward:function(token){

uni.request({

url: interfaces.getDayaward, //获取每日登录奖励

method: 'POST',

data: {

token: token

},

success: (cts) => {

}

});

},

}

module.exports = common;

2、在main.js中 注册

import Vue from 'vue'

import common from './utils/common.js' // 4、公用方法封装为一个文件

//4、挂载在原型common 上,组件内调用: this.common.方法名()

Vue.prototype.common = common

new Vue({

el: '#app',

router,

store,

components: { App },

template: '<App/>'

})

3、在组件中引用

<script>

//这样的局部引用,就没有办法在templete中直接调用了

// import common from '../../utils/common.js'

export default {

mounted() {

// 获取当前时间戳 赋值给nowTime变量,因为是在全局挂载,所以也可以在temple中直接调用

this.nowTime = this.common.nowTime();

// 判断有没有token

if(!this.token){

this.common.getDayaward(); //执行另一个封装好的方法getDayaward()

}

},

}

</script>


vue之封装多个组件调用同一接口的案例

这篇文章主要介绍了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\');

}

};

$http(opt);

return all;

}

console.log(getAll()); // []

$http是在axios基础 进行封装的,是一个异步的方法,所以在组件中调用getAll()方法,拿到的是一个空数组

使用promise进行封装

 export function getAll() {

return new Promise((resolve, reject) => {

let opt = {

method: \'get\',

url: \'all/teacher\',

success: res => {

resolve(res.data.value || []);

},

fail: err => {

reject(err.data.desc);

}

};

$http(opt);

});

}

// 调用

getAll()

.then(data => {

console.log(data); //

})

.catch(err => {

this.tipInfo(err.data.desc, \'提示\', false, \'warning\');

});

使用promise进行封装后,方法,不够简洁,达不到优化的目的

使用回调函数进行封装

export function getAll(callback) {

let opt = {

method: \'get\',

url: \'all/teacher\',

success: res => {

callback(res.data.value || []);

},

fail: err => {

tipInfo(err.data.desc, \'提示\', false, \'warning\');

}

};

$http(opt);

}

// 调用

getAllPark(data => {

console.log(data); // 成功拿到数据

});

补充知识:vue多个页面用到同一个接口的数据( 比如名称列表 ),使用 vuex

第一种: 调接口不传参数

1、在 store文件夹下的 modules文件夹下新建 getName.js

// getName.js

import { getNameList } from \"@/apis/apis\";  // 导入接口

export default {

state: {

nameList: [] // 名称列表

},

mutations: {

changeNameList(state, payload) {

state.nameList= payload;

}

},

actions: {

geName(context) {

getNameList ({}).then(res => {

if (res.code == 0) {

context.commit(\"changeNameList\", res.data);

} else {

Message.error(res.message);

}

});

}

}

};

2、在 store文件夹下 index.js 中引入 getName.js

import getNamefrom \"./modules/getName\";

export default new Vuex.Store({

modules: {

getName

},

});

3、在整个项目刚开始加载的时候就是用 dispatch 分发,这样就不管在哪个页面需要使用到都可以使用

比如打开页面首页的时候,在mounted里面就 dispatch 触发geName函数

<script>

export default {

mounted() {

this.$store.dispatch(\'geName\')

},

}

4、如在多个页面都需要使用 nameList , 以在某一个页面使用为例,其余页面一样用法

<template>

<div>

<el-select v-model=\"form.name\" placeholder=\"请选择名称\" clearable>

<el-option v-for=\"item in nameList\" :key=\"item.id\" :label=\"item.fieldName\" :value=\"item.fieldName\"></el-option>

</el-select>

</div>

</template>

<script>

export default {

computed: {

nameList() {

return this.$store.state.getName.nameList

}

},

}

</script>

第二种: 调接口传参数

import movieService from \'../services/movieService.js\'

export default {

namespaced: true,

state: {

current: 1,

pageSize: 2,

total: 0,

datas: [],

isLoading: false

},

mutations: { //改变状态的通用方法  设置整个状态

setState(state, newState) {

for (const prop in newState) {

state[prop] = newState[prop]

}

}

},

actions: {

fetch(context) { // 根据当前的分页设置,获取电影

context.commit(\"setState\", { isLoading: true })

movieService.getMovies(context.state.current, context.state.pageSize).then(resp => {

console.log(resp)

context.commit(\"setState\", resp)

context.commit(\"setState\", { isLoading: false })

})

}

}

}

// 在 movieService.js

export default {

async getMovies(page, pageSize) {

const datas = await fetch(\"https://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(\"https://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之封装多个组件调用同一接口的案例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。

vue之封装多个组件调用同一接口的案例 (https://www.wpmee.com/) javascript教程 第1张

标签:

提交需求或反馈

Demand feedback