Vue自定义函数挂到全局方法

    技术2022-07-10  122

    方法一:使用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>
    Processed: 0.056, SQL: 9