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 分钟前
写了那么久的前端,你真的了解浏览器背后的“小动作“吗?
前端·程序员·浏览器
wycode3 分钟前
Vue2实践(2)之用component做一个动态表单(一)
前端·javascript·vue.js
维李设论4 分钟前
前端智能化 | AG-UI实践及原理浅析
前端·aigc·agent
第七种黄昏5 分钟前
Vue3 中的 ref、模板引用和 defineExpose 详解
前端·javascript·vue.js
一只卡比兽5 分钟前
动态规划与贪心算法详解:原理、对比与代码实践
前端
aiwery8 分钟前
一文掌握 TypeScript 工具类型:Record、Partial、Omit、Pick 等实战用法
前端·代码规范
ankleless22 分钟前
C语言(12)——进阶函数
前端·html
一条上岸小咸鱼26 分钟前
Kotlin 基本数据类型(四):String
android·前端·kotlin
我是哈哈hh41 分钟前
【Node.js】ECMAScript标准 以及 npm安装
开发语言·前端·javascript·node.js
张元清1 小时前
电商 Feeds 流缓存策略:Temu vs 拼多多的技术选择
前端·javascript·面试