vue中定义全局变量

定义全局变量
设置一个专用的全局变量模块文件,模块里面定义一些变量的初始状态,用export default暴露出去,在main,js里面使用Vue.prototype挂载到vue实例上面或者在其他地方需要使用时,引入该模块即可。
全局变量模块文件
Global.vue文件:

<script>
const serverSrc='www.baidu.com';
const token='12345678';
  export default
  {
    token,//用户token身份
    serverSrc,//服务器地址
  }
</script>

使用方法1
在需要的地方引用进全局变量模块文件,然后通过文件里面的变量名字获取全局变量参数值。

<template>
    <div>{{ token }}</div>
</template>
<script>
import global_ from '../../components/Global'//引用模块进来
export default {
 name: 'text',
data () {
    return {
         token:global_.token,//将全局变量赋值到data里面,也可以直接使用global_.token
        }
    }
}
</script>

使用方法2
在程序入口的main.js文件里面,将上面哪个Global.vue文件挂载到Vue.prototype。

    import global_ from './components/Global'//引用文件
    Vue.prototype.GLOBAL = global_//挂载到Vue实例上面

在整个项目中不需要在应用Global.vue模块文件,直接通过this就可以直接访问Global文件里面定义的全局变量了

<template>
  <div>{{ token }}</div>
</template>

<script>
export default {
name: 'text',
data () {
  return {
       token:this.GLOBAL.token,//直接通过this访问全局变量。
      }
  }
}
</script>	

猜你喜欢

转载自blog.csdn.net/weixin_42292748/article/details/83143824