dependency-injection - Vue2:包含/注入全局实用程序类的正确方法
问题描述
我有 Vue.js 项目,我想在其中使用实用程序类来实现我想在所有模块中使用的功能。
模块/Utils.js
export default class Utils {
array_count (arr) {
return Array.isArray(arr) ? arr.length : 0;
}
}
main.js
import Vue from 'vue';
import Utils from 'modules/Utils';
export default new Vue({
el: '#app',
router,
template: '<App/>',
components: {
App
},
utils: Utils // this has no affect?
});
模块/some.js
import Vue from 'vue';
import Utils from 'modules/Utils'; // I don't want this
var utils = new Utils; // I don't want this
console.log(utils.array_count(['a','b','c']));
我真的不明白如何注入 Utils 类。上面的例子有效 - 但我想摆脱每个模块中 Class 的导入。我想当我将它作为依赖项添加到 main.js 中时,我应该能够在我的项目中的任何地方调用它。
解决方案
当您想从每个组件访问帮助程序时,您可以注册一个全局 mixin。改变你Utils.js
的看起来像一个Mixin。
export default {
methods: {
array_count (arr) {
return Array.isArray(arr) ? arr.length : 0;
}
}
}
然后,导入 mixin 并全局添加。
import Vue from 'vue';
import Utils from 'modules/Utils';
Vue.mixin(Utils);
export default new Vue({
el: '#app',
router,
template: '<App/>',
components: {
App
},
或者,如果您希望某些辅助函数在全局范围内不可用,而仅在某些组件中可用,则可以导入 mixin 并将其手动添加到 Vue 组件中。
推荐阅读
- string - 使用规则约束或子类型 Ada 中的 Unbounded_String?
- java - 当按钮位于 JavaFX 的 BorderPane 中时,有没有办法自动调整按钮大小?
- julia - 使用 Julia 求解 2 变量方程,任何包
- typescript - dtslint $ExpectType 不会减少类型
- html - 当父值更改时,Angular 子组件不会更改值
- python - 如何通过在 Python 中识别单个或多个水平线来分割图像?
- firebase - 没有创建 Firebase 应用“[DEFAULT]” - 调用 Firebase.initializeApp()
- c# - 如果在第二页中使用 INavigationParameter,Xamarin Forms Prism 第一页将无法导航
- r - 如何使用 cur_column 选择列并应用函数?
- python - PRAW 过滤器 NSFW