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
})