vue mount global variable

vue2.x mount global

in main.js file

         Use Vue.prototype.$xxxx=xxxthe form to mount,

this.$xxxGet a variable or method mounted to the global          by

import store from './store'

Vue.prototype.$store = store

Use in the required page vue file

this.$ store.state.username (orange is the variable defined in the store)

vue2.x mount global

Vue3.x mount global

Obviously, the above method will not work

vue3.x mount global

In the main.js file ( note that createApp cannot be created twice, otherwise it will become undefined )

// 挂载全局变量实验
const app = createApp(App);
app.config.globalProperties.$name = 'lhm';
app.use(store).use(router).use(VueAxios, axios).use(ElementPlus, {
  locale: zhCn,
}).mount('#app')

Called in the required page

	import { defineComponent, getCurrentInstance,onMounted} from "vue"

    const { appContext : { config: { globalProperties } } } = getCurrentInstance()
	console.log("全局变量:")
	console.log(globalProperties.$name)

Effect:

Guess you like

Origin blog.csdn.net/enhenglhm/article/details/122662152