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)

        }
相关推荐
钉先生贾38 分钟前
HarmonyOS 7.0 性能排障实战 43:图片与大资源加载抖动时,怎样区分解码、布局与状态更新
java·前端·harmonyos
亿元程序员1 小时前
我的 Cursor 年费会员都还没到期,Cursor 怎么就先没了?原来是马斯克出手了...
前端
polarisya2 小时前
vue搭建知识
前端·javascript·vue.js
map_vis_3d2 小时前
百度地图控件一览:缩放、比例尺、定位、城市列表、地图类型和 3D 导航
前端·javascript·地图·百度地图
Hilaku2 小时前
国内前端面试最离谱的现象:笔试题考手写 Promise.all
前端·javascript·程序员
费曼学习法2 小时前
把规格变成 AI 的输入契约:OpenSpec 在订单状态机重构中的一次落地记录
前端
htzyl2062 小时前
TypeScript中替代enum的五种方案
前端·typescript
hotflyff2 小时前
把 Tesseract 塞进单文件 HTML:浏览器离线 OCR 的完整技术方案
javascript·开源
用户112936112192 小时前
标签数量一个不多一个不少,为什么构建还是报 missing end tag?
前端·vue.js·ai编程
天道kabuto3 小时前
一句话生成整套博客主题:我用 LangGraph 组了个 AI 装修队,自带质检和返工
前端·langchain·ai编程