vuejs如何全局自定义变量
时间:2022-02-11 17:45
方法:设置一个专用的的全局变量模块文件,模块里面定义一些变量初始状态,用“export default”暴露出去,在“main.js”里面使用“Vue.prototype”挂载到vue实例上面或者在其它地方需要使用时,引入该模块便可。 本教程操作环境:windows7系统、vue2.9.6版,DELL G3电脑。 设置一个专用的的全局变量模块文件,模块里面定义一些变量初始状态,用export default 暴露出去,在main.js里面使用Vue.prototype挂载到vue实例上面或者在其它地方需要使用时,引入该模块便可。 Global.vue文件: 在需要的地方引用进全局变量模块文件,然后通过文件里面的变量名字获取全局变量参数值。 在text1.vue组件中使用: 在程序入口的main.js文件里面,将上面那个Global.vue文件挂载到Vue.prototype。 接着在整个项目中不需要再通过引用Global.vue模块文件,直接通过this就可以直接访问Global文件里面定义的全局变量。 text2.vue: 相关推荐:《vue.js教程》 以上就是vuejs如何全局自定义变量的详细内容,更多请关注gxlsystem.com其它相关文章!定义全局变量
原理:
全局变量模块文件:
<script>
const serverSrc='www.baidu.com';
const token='12345678';
const hasEnter=false;
const userSite="中国钓鱼岛";
export default
{
userSite,//用户地址
token,//用户token身份
serverSrc,//服务器地址
hasEnter,//用户登录状态
}
</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>
<style scoped>
</style>
使用方式2:
import global_ from './components/Global'//引用文件
Vue.prototype.GLOBAL = global_//挂载到Vue实例上面
<template>
<div>{{ token }}</div>
</template>
<script>
export default {
name: 'text',
data () {
return {
token:this.GLOBAL.token,//直接通过this访问全局变量。
}
}
}
</script>
<style scoped>
</style>
Vuex也可以设置全局变量