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

本教程操作环境:windows7系统、vue2.9.6版,DELL G3电脑。
设置一个专用的的全局变量模块文件,模块里面定义一些变量初始状态,用export default 暴露出去,在main.js里面使用Vue.prototype挂载到vue实例上面或者在其它地方需要使用时,引入该模块便可。
Global.vue文件:
<script>
const serverSrc='www.baidu.com';
const token='12345678';
const hasEnter=false;
const userSite="中国钓鱼岛";
export default
{
userSite,//用户地址
token,//用户token身份
serverSrc,//服务器地址
hasEnter,//用户登录状态
}
</script>在需要的地方引用进全局变量模块文件,然后通过文件里面的变量名字获取全局变量参数值。
立即学习“前端免费学习笔记(深入)”;
在text1.vue组件中使用:
<template>
<div>{{ token }}</div>
</template>
<script>
import global_ from '../../components/Global'//引用模块进来
export default {
name: 'text',
data () {
return {
token:global_.token,//将全局变量赋值到data里面,也可以直接使用global_.token
}
}
}
</script>
<style scoped>
</style>在程序入口的main.js文件里面,将上面那个Global.vue文件挂载到Vue.prototype。
import global_ from './components/Global'//引用文件 Vue.prototype.GLOBAL = global_//挂载到Vue实例上面
接着在整个项目中不需要再通过引用Global.vue模块文件,直接通过this就可以直接访问Global文件里面定义的全局变量。
text2.vue:
<template>
<div>{{ token }}</div>
</template>
<script>
export default {
name: 'text',
data () {
return {
token:this.GLOBAL.token,//直接通过this访问全局变量。
}
}
}
</script>
<style scoped>
</style>相关推荐:《vue.js教程》
以上就是vuejs如何全局自定义变量的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号