1、定义全局变量
设置一个专用的的全局变量模块文件,模块里面定义一些变量初始状态,用export default 暴露出去,在main.js里面使用Vue.prototype挂载到vue实例上面或者在其它地方需要使用时,引入该模块便可。
1.1 全局变量模块文件 Global.vue文件
<script>
const serverSrc='www.baidu.com';
const token='12345678';
const hasEnter=false;
const userSite="中国钓鱼岛";
export default
{
userSite,//用户地址
token,//用户token身份
serverSrc,//服务器地址
hasEnter,//用户登录状态
}
</script>
1.2 使用方式1
在需要的地方引用进全局变量模块文件,然后通过文件里面的变量名字获取全局变量参数值。
在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 lang="scss" scoped>
</style>
1.3 使用方式2:
在程序入口的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 lang="scss" scoped>
</style>
2、定义全局函数
原理
新建一个模块文件,然后在main.js里面通过Vue.prototype将函数挂载到Vue实例上面,通过this.函数名,来运行函数。
2.1 在main.js里面直接写函数
简单的函数可以直接在main.js里面直接写
Vue.prototype.changeData = function (){//changeData是函数名
alert('执行成功');
}
组件中调用:
this.changeData();//直接通过this运行函数
2.2 写一个模块文件,挂载到main.js上面。
base.js文件,文件位置可以放在跟main.js同一级,方便引用
exports.install = function (Vue, options) {
Vue.prototype.text1 = function (){//全局函数1
alert('执行成功1');
};
Vue.prototype.text2 = function (){//全局函数2
alert('执行成功2');
};
};
main.js入口文件:
import base from './base'//引用
Vue.use(base);//将全局函数当做插件来进行注册
组件里面调用:
this.text1();
this.text2();
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/117217.html