0


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

首先

声明Vue

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

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

<script>const name ='ZhangSan';//名称const address ='No.20, Taihu Road';//地址exportdefault{
        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 暴露出去。

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

// 判断是否显示logoconst logo =true;exportdefault{
  logo
};

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

在这里插入图片描述

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

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

在这里插入图片描述

页面使用

在这里插入图片描述


本文转载自: https://blog.csdn.net/Maxueyingying/article/details/128676622
版权归原作者 蓝胖子的多啦A梦 所有, 如有侵权,请联系我们删除。

“【Vue】全局变量的定义及使用”的评论:

还没有评论