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)

        }
相关推荐
2401_837088502 分钟前
CSS vertical-align
前端·html
优雅永不过时·8 分钟前
实现一个漂亮的Three.js 扫光地面 圆形贴图扫光
前端·javascript·智慧城市·three.js·贴图·shader
揣晓丹1 小时前
JAVA实战开源项目:健身房管理系统 (Vue+SpringBoot) 附源码
java·vue.js·spring boot·后端·开源
景尘1 小时前
vue3 全局注册自定义指令,input聚焦失焦展示对应值
vue.js
CodeCraft Studio1 小时前
报表控件stimulsoft教程:使用 JoinType 关系参数创建仪表盘
前端·ui
春天姐姐2 小时前
vue知识点总结 依赖注入 动态组件 异步加载
前端·javascript·vue.js
互联网搬砖老肖3 小时前
Web 架构之数据读写分离
前端·架构·web
Pop–4 小时前
Vue3 el-tree:全选时只返回父节点,半选只返回勾选中的节点(省-市区-县-镇-乡-村-街道)
开发语言·javascript·vue.js
滿4 小时前
Vue3 + Element Plus 动态表单实现
javascript·vue.js·elementui
钢铁男儿4 小时前
C# 方法(值参数和引用参数)
java·前端·c#