在 Vue.js项目中如何定义全局变量&全局函数

在项目中,经常有些函数和变量是需要复用,比如说网站服务器地址,从后台拿到的:用户的登录 token, 用户的地址信息等,这时候就需要设置一波全局变量和全局函数。

目录

          定义全局变量

定义全局函数


定义全局变量

原理:设置一个专用的的全局变量模块文件,模块里面定义一些变量初始状态,用 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>

方法一:

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

    <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>

方法二:

在程序入口的 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>

定义全局函数

原理:新建一个模块文件,然后在 main.js 里面通过 Vue.prototype 将函数挂载到 Vue 实例上面,通过 this. 函数名,来运行函数。

方法一:

在 main.js 里面直接写函数

Vue.prototype.changeData = function (){//changeData是函数名
  alert('执行成功');
}

组件中调用:

js this.changeData();//直接通过this运行函数

方法二:

写一个模块文件,挂载到 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 入口文件:

javascript import base from './base'//引用 Vue.use(base);//将全局函数当做插件来进行注册

组件里面调用:

javascript this.text1(); this.text2();

另一个例子:

import  {ToastPlugin} from 'vux'  //全局引入这个组件

main.js全局引入
//封装消息提示
Vue.prototype.msg = function (text) { 
//如果你需要让一个工具函数在每个组件可用,可以把方法挂载到 Vue.prototype上。那么组件代码里this.method()
    Vue.$vux.toast.show({
        text: text,
        type: 'text'
    })
}
//然后在其他vue文本里用this.msg('内容')
//则会自动弹出内容提示;

来源于:

http://www.cnblogs.com/liuyishi/

https://blog.csdn.net/liang377122210/article/details/76853117

猜你喜欢

转载自blog.csdn.net/weixin_41888813/article/details/83784075
今日推荐