vue2.x挂载全局
在main.js文件中
使用Vue.prototype.$xxxx=xxx
的形式来挂载,
通过this.$xxx
来获取挂载到全局的变量或者方法
import store from './store'
Vue.prototype.$store = store
在需要的页面vue文件中使用
this.$store.state.username (橙色为store里定义的变量)
Vue3.x挂载全局
显然,用上面的方法是不行的
main.js文件中 (注意createApp不能create两次,否则会变成undefined)
// 挂载全局变量实验
const app = createApp(App);
app.config.globalProperties.$name = 'lhm';
app.use(store).use(router).use(VueAxios, axios).use(ElementPlus, {
locale: zhCn,
}).mount('#app')
需要的页面中调用
import { defineComponent, getCurrentInstance,onMounted} from "vue"
const { appContext : { config: { globalProperties } } } = getCurrentInstance()
console.log("全局变量:")
console.log(globalProperties.$name)
效果: