方法一:使用Vue.prototype

//在mian.js中写入函数

Vue.prototype.getToken = function (){
  ...
}

//在所有组件里可调用函数

this.getToken();

方法二:使用exports.install+Vue.prototype

// 写好自己需要的fun.js文件

exports.install = function (Vue, options) {
    Vue.prototype.getToken = function (){
       ...
    };
};

// main.js 引入并使用

import fun from './fun'
Vue.use(fun);

//在所有组件里可调用函数

this.getToken();

在用了exports.install方法时,运行报错exports is not defined

解决方法

export default {
    install(Vue)  {
        Vue.prototype.getToken = {
           ...
        }
    }
}

方法三:使用全局变量模块文件

Global.vue文件:

<script>
    const token='12345678';

    export default {
        methods: {
            getToken(){
                ....
            }
        }
    }
</script>

在需要的地方引用进全局变量模块文件,然后通过文件里面的变量名字获取全局变量参数值。

<script>
import global from '../../components/Global'//引用模块进来
export default {
    data () {
        return {
            token:global.token
        }
    },
    created: function() {
        global.getToken();
    }
}
</script>

 

Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐