【问题标题】:How to import my own class or method globally in Vue?如何在 Vue 中全局导入我自己的类或方法?
【发布时间】:2019-12-27 10:15:48
【问题描述】:

我有一个需要全局导入的类和方法,这样我就可以避免在每个 Vue 文件中再次导入它。我通常像这样在每个 Vue 文件中导入自己的类和方法:

// in myFunc.js
export const fn = {
  myFunc: function(param) { alert(param) }
}

// then I use it like this
import {fn} from '@/assets/js/myFunc.js';
fn.myFunc('Lorem ipsum');

main.js,我试过下面的代码,还是不行:

import {fn} from '@/assets/js/myFunc.js';

Vue.mixin({
  components: { fn },
})

如何全局导入类/方法?

【问题讨论】:

    标签: vue.js vuejs2


    【解决方案1】:
    import Vue from 'vue'
    import { fn } from '@/assets/js/myFunc.js';
    
    Vue.prototype.$fn = fn
    

    然后在你的组件中。

    this.$fn.myFunc()
    

    Adding Instance Properties.

    您可能希望在许多组件中使用数据/实用程序,但是 你不想污染全局范围。在这些情况下,您可以 通过在 原型。

    【讨论】:

    • this.$fn.myFunc(); 可以了,顺便说一句,我们可以在不写this.$fn.myFunc() 的情况下调用该方法,只需myFunc() ??,
    • 是的,要实现这一点,您应该污染全局对象(浏览器中的window - window.myFunc = function() { console.log('I am in the global scope!') })。但这被认为是一种不好的做法。
    猜你喜欢
    • 1970-01-01
    • 2014-09-11
    • 1970-01-01
    • 2019-01-06
    • 2016-05-04
    • 2018-10-26
    • 2017-12-19
    • 1970-01-01
    • 2021-02-15
    相关资源
    最近更新 更多