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)

        }
相关推荐
揣晓丹3 分钟前
JAVA实战开源项目:共享汽车管理系统(Vue+SpringBoot) 附源码
java·开发语言·vue.js·spring boot·开源
程序员黄同学18 分钟前
解释 TypeScript 中的枚举(enum),如何使用枚举定义一组常量?
javascript·ubuntu·typescript
Xlbb.24 分钟前
SpiderX:专为前端JS加密绕过设计的自动化工具
前端·javascript·自动化
beibeibeiooo30 分钟前
【ES6】01-ECMAScript基本认识 + 变量常量 + 数据类型
前端·javascript·ecmascript·es6
庸俗今天不摸鱼1 小时前
【万字总结】前端全方位性能优化指南(三)
前端·性能优化·gpu
前端南玖1 小时前
深入理解Base64编码原理
前端·javascript
aircrushin1 小时前
【PromptCoder + Trae 最新版】三分钟复刻 Spotify 页面
前端·人工智能·后端
木木黄木木2 小时前
从零开始实现一个HTML5飞机大战游戏
前端·游戏·html5
NoneCoder2 小时前
工程化与框架系列(30)--前端日志系统实现
前端·状态模式