首頁  >  文章  >  web前端  >  vue.js如何宣告全域變數

vue.js如何宣告全域變數

coldplay.xixi
coldplay.xixi原創
2020-11-19 11:08:154032瀏覽

vue.js宣告全域變數的方法:先設定專用的的全域變數模組文件,模組裡面定義一些變數初始狀態;然後用export default曝光;最後在【main.js】裡面使用【 Vue.prototype】掛載到vue實例上面,引入此模組即可。

vue.js如何宣告全域變數

本教學操作環境:windows7系統、vue2.9版,此方法適用於所有品牌電腦。

vue.js宣告全域變數的方法:

定義全域變數

原理: 設定一個專用的的全域變數模組文件,模組裡面定義一些變數初始狀態,用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>

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

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

方法二: 在程式入口的 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>

相關免費學習推薦:JavaScript(影片)

以上是vue.js如何宣告全域變數的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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