#我的用例
我有一个 utils mixin 模块,它将 lodash 作为方法注入(inject) .vue
( single file components ) 组件:
// utilsMixin.js
import _ from 'lodash';
import moment from 'moment';
export default {
computed: {
_: () => _,
moment: () => moment,
},
};
// main.js
// ...
import utilsMixin from './utilsMixin';
Vue.mixin(utilsMixin);
因此,我所有的项目都可以使用_
和moment
作为方法。
#问题
如果我使用 _
在 <template>
部分,没有 linter 问题,如 _
隐藏在this
里面来自 vue 的变量:
// MyFancyComponent.vue
<template>
<myComponent
v-for="item in _.get(this, 'myObject.collection', [])"
>
<div> {{ item }} </div>
</myComponent>
但是当我在<script>
中使用它时部分:
// MyFancyComponent.vue
// ...
<script>
export default {
name: 'MyFancyComponent',
methods: {
find: ()=> _.find // [eslint] '_' is not defined. [no-undef]
};
</script>
Eslint 来自 [eslint] '_' is not defined. [no-undef]
的投诉问题,但我仍然可以在不导入的情况下使用它 _
,我可以通过声明全局 lodash 来阻止 linter 提示:
/* global _ */
请注意,我还有其他 .js
没有 lodash 为全局的文件,如果我在那里使用 lodash,我需要 linter 来提示:
#预期行为
我希望“_”仅在我的 vue 单文件组件中被检测为全局变量,但在我的 JavaScript 文件中未定义(因此我需要在 .js
文件中导入 lodash)。
#直观的解决方案
我希望能够在 .eslintrc.js
内配置全局变量这只适用于单文件组件。作为一种方法,它可能看起来像:
// .eslintrc.js
// ...
globals: {
vue: {
'_': false,
moment: false
},
js: {
process: false,
isFinite: true
}
},
// ...
最佳答案
您的问题是您缺少 Vue.js 如何将其注入(inject)到您的组件中。如果您在 Vue.js 中(在脚本中)正确使用 Mixin,它将如下所示:
// MyFancyComponent.vue
// ...
<script>
export default {
name: 'MyFancyComponent',
methods: {
find(...args) {
return this._.find.bind(this._, args);
}// [eslint] '_' is not defined. [no-undef]
};
</script>
您使用 this._
来引用 Lodash,因为您已将其绑定(bind)到组件的实例,而不是使其成为全局引用的对象。它工作的原因,但 ESLint 提示是因为你已经将库作为全局对象导入到 mixin 中,但你没有在这个特定文件中导入它,所以 ESLint 提示是因为它不知道你这样做了另一个文件中的全局导入并将其绑定(bind)到每个组件,以使其可供这些单独的组件使用。
关于javascript - 如何设置 eslint 以仅在单文件 vue 组件中将 lodash 检测为全局?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54345272/