首頁  >  文章  >  web前端  >  vuejs如何全域自訂變數

vuejs如何全域自訂變數

青灯夜游
青灯夜游原創
2021-09-18 18:04:331740瀏覽

方法:設定一個專用的全域變數模組文件,模組裡面定義一些變數初始狀態,用「export default」暴露出去,在「main.js」裡面使用「Vue.prototype」掛載到vue實例上面或在其它地方需要使用時,引入該模組便可。

vuejs如何全域自訂變數

本教學操作環境:windows7系統、vue2.9.6版,DELL G3電腦。

定義全域變數

原理:

設定一個專用的的全域變數模組文件,模組裡面定義一些變數初始狀態,用export default 暴露出去,在main. js裡面使用Vue.prototype掛載到vue實例上面或在其它地方需要使用時,引入該模組便可。

全域變數模組檔案:

Global.vue檔案:

<script>
const serverSrc=&#39;www.baidu.com&#39;;
const token=&#39;12345678&#39;;
const hasEnter=false;
const userSite="中国钓鱼岛";
  export default
  {
    userSite,//用户地址
    token,//用户token身份
    serverSrc,//服务器地址
    hasEnter,//用户登录状态
  }
</script>

使用方式1:

在需要的地方引用進全域變數模組文件,然後透過檔案裡面的變數名字來取得全域變數參數值。

在text1.vue元件中使用:

<template>
    <div>{{ token }}</div>
</template>

<script>
import global_ from &#39;../../components/Global&#39;//引用模块进来
export default {
 name: &#39;text&#39;,
data () {
    return {
         token:global_.token,//将全局变量赋值到data里面,也可以直接使用global_.token
        }
    }
}
</script>
<style scoped>

</style>

使用方式2:

在程式入口的main.js檔案裡面,將上面那個Global.vue檔案掛載到Vue.prototype。

 import global_ from &#39;./components/Global&#39;//引用文件
 Vue.prototype.GLOBAL = global_//挂载到Vue实例上面

接著在整個專案中不需要再透過引用Global.vue模組文件,直接透過this就可以直接存取Global文件裡面定義的全域變數。

text2.vue:

<template>
    <div>{{ token }}</div>
</template>

<script>
export default {
 name: &#39;text&#39;,
data () {
    return {
         token:this.GLOBAL.token,//直接通过this访问全局变量。
        }
    }
}
</script>
<style scoped>
</style>

Vuex也可以設定全域變數

相關推薦:《vue.js教學

以上是vuejs如何全域自訂變數的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn