乐趣区

关于javascript:Vue3-全局挂在方法和属性

第一步

import {createApp} from 'vue'
import App from './App.vue';
const app = createApp(App);
app.config.globalProperties.foo = 'bar'
app.config.globalProperties.test = 'bar'
app.mount('#app')

第二步

创立 useCurrentInstance.ts 文件

import {ComponentInternalInstance, getCurrentInstance} from 'vue'
export default function useCurrentInstance() {const { appContext} = getCurrentInstance() as ComponentInternalInstance
    const ctx = appContext.config.globalProperties;
    return {ctx}
}

第三步

import useCurrentInstance from "../useCurrentInstance";// 依据本人创立的门路引入
setup: () => {const { ctx} = useCurrentInstance();
    const getFoo = () => {console.log(ctx) //{foo: "bar" test: "bar"}
      
    }
    return {getFoo}
  }
退出移动版