(二十一)js全局文件 全局变量挂载 Vue.prototype

(二十一) js全局文件 全局变量挂载 Vue.prototype

目的:就是用些全局的变量,比如一些你自定义的ip 啥的,那为啥不用vuex。我就不,我就用这个
当然了,也有点不一样吗

所以我们分两种,

1.一种是直接写在文件里面直接调用
2.挂载到Vue.prototype 这样就成了一个全局的对象

首先新建文件:(一般新建在src下面,和main.js 平齐,你放在assets里面也行)
overallData,js

<script>
const address='www.baidu.com';
const ='12345678';
const state=false;
const ip="127.0.0.1";
  export default
  {
    address,//用户地址
    token,//用户token身份
    ip,//服务器地址
    state,//用户登录状态
  }
</script>

反正你能把你需要的export出来就行

第一种:直接引用使用取值

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

第二种:挂载数据 在 main.js 文件里面,将上面那个 overallData.vue 文件挂载到 Vue.prototype。

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

使用

<template>
    <div>{{ token }}</div>
</template>
<script>
    export default {
        name: 'text',
        data () {
            return {
                 token:this.overallData.token,//直接通过this访问全局变量。
                }
            }
    }
</script>
<style lang="scss" scoped>
</style>

全局函数

举例子:
第一种全局文件
overallData,js

export default {
    ws: {},
    setWs: function(newWs) {
        this.ws = newWs
    },
}
import overallData from './components/Global'//引用文件
this.overallData .setWs(client);

第二种直接在main.js里面进行声明挂载

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

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

第三种挂载到全局,使用插件的方式进行注册挂载

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();

第三种基本上没用过,其实为了方便,怎么着都可以,全局挂载我感觉不常用,就是觉得,要是不挂载,就还知道,这是个公共文件里面的,挂载了,直接this是方便,但是小别扭,开心就好

重要注意

你会发现
Vue.use();
Vue.prototype
Vue.prototype .$名称

相关区别:
Vue.use() 加载插件 ,必须要是一个对象
还有写不写$的用法 https://blog.csdn.net/qq_32407233/article/details/83819831
相关区别https://segmentfault.com/a/1190000019611146

原文地址:https://www.cnblogs.com/tcz1018/p/14069710.html