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)

        }
相关推荐
kirinlau2 分钟前
Vue.observable实现vue原生轻量级状态管理详解
前端·javascript·vue.js
严文文-Chris3 分钟前
RAG关键技术要点详解
java·服务器·前端
自然 醒4 分钟前
elementUI的select下拉框如何下拉加载数据?
前端·javascript·elementui
我没想到原来他们都是一堆坏人5 分钟前
常用npm源与nrm
前端·npm·node.js
编代码的小王8 分钟前
【无标题】
前端·css
仰望.15 分钟前
vxe-table 按多个列进行分组和按多个字段进行分组的使用方式
vue.js·vxe-table
im_AMBER16 分钟前
React 20 useState管理组件状态 | 解构 | 将事件处理函数作为 props 传递 | 状态提升
前端·javascript·笔记·学习·react.js·前端框架
小oo呆17 分钟前
【自然语言处理与大模型】LangChainV1.0入门指南:核心组件Tools
前端·javascript·easyui
亿元程序员22 分钟前
你知道三国志战略版是怎么实现横竖屏动态切换的吗?
前端