vue設置全局變量和修改


 

1. 只讀的全局變量

對於只讀的全局變量,知道的有以下兩種使用方式:

1)global.js 模塊中定義;其他模塊import后再使用即可

1.1)定義

import Vue from 'vue';

let MyComm = new Vue({
    methods: {
        deleteCookie: function (cname) {
            let d = new Date();
            let expires = "expires=" + d.toGMTString();
            document.cookie = cname + "=; " + expires;
        }
})

export default MyComm;

1.2)引用

import MyComm from "./components/common/comm";
MyComm.deleteCookie('ms_username')

 

 

2)gobal.js 模塊中定義,並綁定到 prototype,其他任何Vue實例可直接引用 this.$xxxx

2.1)定義,綁定&引用

import Vue from 'vue';

let MyComm = new Vue({
    methods: {
        deleteCookie: function (cname) {
            let d = new Date();
            let expires = "expires=" + d.toGMTString();
            document.cookie = cname + "=; " + expires;
        }
})

export default MyComm;
Vue.prototype.$MyComm = MyComm;
//項目中任何地方都可如此引用 
this.$MyComm.deleteCookie('ms_username')

 

2.可讀寫的全局變量 

如果想隨時修改全局變量的值,有一種辦法:main.js中data定義,其他地方通過 this.$root.{paramName} 來引用/修改

2.1)main.js 中定義

new Vue({
    router,
    data: function(){
        return {
            URL: 'http://localhost:8080',
        }
    },
    render: h => h(App)
}).$mount('#app');

 

 

2.2)引用

// 修改
this.$root.URL= "xxxxx" 

// 引用
let URL = this.$root.URL

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM