vue3将接口注册成全局方法

1、在api文件写接口

//api.js
export function getist() {
    return request({
        url: '/sty/getList',
        method: 'get'
    })
}

2、在main.js入口文件中注册为全局方法

globalProperties是挂载在vue实例上面的,所以可以直接在template里面访问。

import { createApp } from 'vue'
import App from './App'
const app = createApp(App)
import getList from '@/api/api.js'

// 全局方法挂载
app.config.globalProperties.getList = getList;

3、在页面中使用,获取main里面的方法

vue3中通过getCurrentInstance()获取当前组件实例,相当于vue2的this对象。然后解构出proxy代理对象,通过访问代理对象来间接访问当前组件的实例对象。proxy能够调用在main.js文件注册的全局方法和全局属性。

const { proxy } = getCurrentInstance();
const list = ref()

proxy.getList().then(res => {
  list.value = res.data
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值