【Vue】全局变量的定义及使用

首先声明Vue使用全局变量的方法有很多,以下只是个人觉得比较简洁的2种。其中两者的第一步操作相同,即:

创建全局变量文件Global.vue,内容如下:

<script>
    const name = 'ZhangSan'; //名称
    const address = 'No.20, Taihu Road'; //地址

    export default {
    
    
        name,
        address
    }
</script>

方法1:在main.js中直接将全局变量挂载到Vue.prototype

import global from '../components/xx/Global'
Vue.prototype.GLOBAL = global;

用时不用任何多余操作,直接调用this.GLOBAL.name即可。

方法2:在需要使用全局变量的页面引入global再使用

import global from '../components/xx/Global'
data() {
    
    
        return {
    
    
                userName: global.name,
                userAddress: global.address
        }
}

第一步:单独新建一个全局变量模块文件,模块中定义一些变量初始状态,用export default 暴露出去。

在这里插入图片描述
在这里插入图片描述

// 判断是否显示logo
const logo = true;
export default {
    
    
  logo
};

第二步:在main.js中引入,并通过Vue.prototype挂载到vue实例上面。供其他模块文件使用;

在这里插入图片描述

// 全局环境变量
import showLogo from '../public/showLogo.js'
Vue.prototype.$showLogo = showLogo;

第三步:在需要的模块文件中引入并使用;

在这里插入图片描述

页面使用

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Maxueyingying/article/details/128676622