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)

        }
相关推荐
前端老鹰几秒前
JavaScript Array.prototype.some ():数组判断的 “快捷侦探”
前端·javascript
张元清1 分钟前
揭秘JS事件循环:一道字节跳动面试题带你深入理解async/await、Promise与RAF
前端·react.js·面试
KenXu4 分钟前
F2C-Chrome插件-Figma免费的DevMode来了!
前端
北海几经夏10 分钟前
React组件中的this指向问题
前端·react.js
程序媛李李李李李蕾16 分钟前
你不能直接用现成的吗?整个前端做笔记管理工具真是折腾人
javascript·vue.js·后端
passer98123 分钟前
列表项切换时同步到可视区域
前端
FogLetter25 分钟前
移动端适配的终极奥义:从lib-flexible到postcss-pxtorem的全方位指南
前端·postcss
易元26 分钟前
设计模式-访问者模式
前端·后端·设计模式
兵临天下api26 分钟前
Elasticsearch 查询性能优化:从 3 秒到 300ms 的 6 个核心参数调优指南
前端
整点可乐27 分钟前
cesium实现鹰眼图
javascript·cesium