【vue3】vue3注册全局方法、全局属性

  1. 创建方法文件
// /src/assets/scripts/http.js
function http(){}
export default http;
  1. 挂载到vue原型链
// main.js
import { createApp } from 'vue'
import App from '/@/App.vue'
const app = createApp(App)

import http from './assets/scripts/http.js'
app.config.globalProperties.$http = http;  // 注册全局方法
app.config.globalProperties.$global_var = 'hello word'; // 注册全局属性


app.mount('#app')
  1. 组件中使用
import {getCurrentInstance} from 'vue'
export default {
    setup(){
          const {proxy} = getCurrentInstance();
          console.log(proxy.$http)
          console.log(proxy.$global_var)
    }
}

你可能感兴趣的:(【vue3】vue3注册全局方法、全局属性)