Vue引入外部异步js函数并接收返回值

export default 和export :
javascript 复制代码
 myModule.js

//export default 只能出现一次,在引入的时候直接写,不用在花括号里面结构赋值
export default function defaultFunction() {
  console.log('This is the default function');
}

export function anotherFunction() {
  console.log('This is another function');
}

export const myVariable = 'This is myVariable';

// 另一个文件
import defaultFunc, { anotherFunction, myVariable } from './myModule';
defaultFunc(); // 输出:This is the default function
anotherFunction(); // 输出:This is another function
console.log(myVariable); // 输出:This is myVariable
场景:

在Vue项目里面,外部定义一个upload.js文件,在里面执行异步上传的upFile函数。在Fille.vue里面引用并接受函数返回值。

javascript 复制代码
test.js


写法一 async 与 await:
const axios = require('axios');
export async function up(data) {

    let result = await axios({
        method: 'post',
        url: `api接口`,
        data: { eventNam: data },
        headers: {
            token: localStorage.getItem('token')
        }
    })
    return result   需要在外部返回

}


写法二 new Promise:

const axios = require('axios');
export function up(data) {
    return new Promise((resolve) => {
        axios({
            method: 'post',
            url: `https://lendingapi-sit.dowsure.com/lending/event/add`,
            data: { eventNam: data },
            headers: {
                token: localStorage.getItem('token')
            }
        })
            .then(res => {
                resolve(res.data)
            });

    })
}



写法三:

const axios = require('axios');

export async function up(data) {
    let result = ''  //获取函数返回值
    await axios({
        method: 'post',
        url: `https://lendingapi-sit.dowsure.com/lending/event/add`,
        data: { eventNam: data },
        headers: {
            token: localStorage.getItem('token')
        }
    })
        .then(res => {
            result = res.data
        });
    return result //获取函数返回值   需要在外部返回
}
javascript 复制代码
File.vue

<el-button @click="getTest">调用异步函数</el-button>

import { up } from "@/api/test"
async getTest() {
     
          let res = await up(111)

        }
相关推荐
Можно9 分钟前
深入理解 ES6 Proxy:与 Object.defineProperty 的全面对比
前端·javascript·vue.js
Birdy_x23 分钟前
接口自动化项目实战(1):requests请求封装
开发语言·前端·python
天天向上10242 小时前
vue el-table实现拖拽排序
前端·javascript·vue.js
西西学代码2 小时前
Flutter---回调函数
开发语言·javascript·flutter
卷帘依旧2 小时前
JavaScript 闭包经典问题:为什么输出 10 次 i=10
javascript
柳杉3 小时前
Three.js × Blender:从建模到 Web 3D 的完整工作流深度解析
前端·javascript·数据可视化
reembarkation4 小时前
vue3中使用howler播放音频列表
前端·vue.js·音视频
手握风云-4 小时前
基于 Java 的网页聊天室(三)
服务器·前端·数据库
weixin199701080164 小时前
《识货商品详情页前端性能优化实战》
前端·性能优化
Forever7_4 小时前
重磅!Vue3 手势工具正式发布!免费使用!
前端·前端框架·前端工程化