vue.js中定義全域變數的方法:1、在需要的地方引用進全域變數模組文件,並透過文件裡面的變數名字取得全域變數參數值;2、在程式入口的【main .js】檔案裡面,將【Global.vue】檔案掛載到【Vue.prototype】。

本教學操作環境:windows10系統、vue2.5.2,本文適用於所有品牌的電腦。
【相關文章推薦:vue.js】
#vue.js中定義全域變數的方法:
原理: 設定一個專用的全域變數模組文件,模組裡面定義一些變數初始狀態,用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 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 scoped>
</style>相關免費學習推薦:JavaScript(影片)
以上是vue.js中如何定義全域變數的詳細內容。更多資訊請關注PHP中文網其他相關文章!