> 文章列表 > 【前端】VUE3 在原型上挂载全局方法变量

【前端】VUE3 在原型上挂载全局方法变量

【前端】VUE3 在原型上挂载全局方法变量

【前端】VUE3 在原型上挂载全局方法变量

1

main.js

const app = createApp(App);app.config.globalProperties.$全局变量 = '我是全局变量'

2配置App.vue

<script>
import HelloWorld from './components/HelloWorld.vue'
import {getCurrentInstance} from "vue";export default {name: 'App',components: {HelloWorld}, setup(){//在这里定义全局// const {ctx} = getCurrentInstance();  //  方式一,这种方式只能在开发环境下使用,生产环境下的ctx将访问不到console.log('挂载全局变量 start')const internalInstance  = getCurrentInstance(); //  方式二,此方法在开发环境以及生产环境下都能放到组件上下文对象(推荐)const globalProperties = internalInstance.appContext.config.globalPropertiesconst $全局变量= globalProperties.$全局变量console.log($全局变量)console.log('挂载全局变量 end')},
}
</script>

3 全局使用 在其他vue页面种 直接这样使用

console.log(this.$全局变量)