模块化之后,想用js全局变量,遇到点困难。搜索资料后搞定,大概2个步骤:

1、定义一个vue模块,const定义变量,并用export对外暴露.

Globle.vue

<script>
// 服务端url
    const SERVER_BASE_URL = 'http://10.199.xxx.x0:8081/'
    export default{
        SERVER_BASE_URL
    }
</script>

2、在用到全局变量的模块,import后再使用

test.vue

import global_ from 'components/common/Global.vue'
console.log(global_.SERVER_BASE_URL)

 ------------------------------2018/12/27 定义component.js并在main.js中引用----------------------------

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;
        },

        getCookie: function (cname) {
            let name = cname + "=";
            let ca = document.cookie.split(';');
            for (let i = 0; i < ca.length; i++) {
                let c = ca[i].trim();
                if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
            }
            return "";
        },

        setCookie: function (cname, cvalue, exdays) {
            let d = new Date();
            d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
            let expires = "expires=" + d.toGMTString();
            document.cookie = cname + "=" + cvalue + "; " + expires;
        }
    }
})

export default MyComm;

2. main.js中引用

import MyComm from "./components/common/comm";

const role = MyComm.getCookie('ms_username')

 

posted on 2018-01-04 17:40  蛋尼  阅读(2101)  评论(0编辑  收藏  举报