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

42次阅读

共计 605 个字符,预计需要花费 2 分钟才能阅读完成。

第一步

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

正文完
 0