(二十一) 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