Vue | npm运行发球| ESLint全局变量未在组件内定义 [英] Vue | npm run serve | ESLint global variable is not defined within a component
问题描述
我正在这样的 main.js
窗口中设置一个vue实例:
I am setting a vue instance on the window in my main.js
like this:
window.todoEventBus = new Vue()
在我正在尝试的组件内部像这样访问此todoEventBus全局对象:
Inside my components I am trying to access this todoEventBus global object like this:
created() {
todoEventBus.$on('pluralise', this.handlePluralise);
},
但我收到错误消息:
Failed to compile.
./src/components/TodoItem.vue
Module Error (from ./node_modules/eslint-loader/index.js):
error: 'todoEventBus' is not defined (no-undef) at src\components\TodoItem.vue:57:9:
55 |
56 | created() {
> 57 | todoEventBus.$on('pluralise', this.handlePluralise);
| ^
58 | },
59 |
60 | methods: {
1 error found.
但是如果我console.log todoEventBus,我会看到vue对象。
However if I console.log todoEventBus I see the vue object.
我的package.json文件如下。
My package.json file looks like this.
{
"name": "todo-vue",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},
"dependencies": {
"core-js": "^3.3.2",
"vue": "^2.6.10"
},
"devDependencies": {
"@vue/cli-plugin-babel": "^4.0.0",
"@vue/cli-plugin-eslint": "^4.0.0",
"@vue/cli-service": "^4.0.0",
"babel-eslint": "^10.0.3",
"eslint": "^5.16.0",
"eslint-plugin-vue": "^5.0.0",
"sass": "^1.23.1",
"sass-loader": "^8.0.0",
"vue-template-compiler": "^2.6.10"
},
"eslintConfig": {
"root": true,
"env": {
"node": true
},
"extends": [
"plugin:vue/essential",
"eslint:recommended"
],
"rules": {},
"parserOptions": {
"parser": "babel-eslint"
}
},
"postcss": {
"plugins": {
"autoprefixer": {}
}
},
"browserslist": [
"> 1%",
"last 2 versions"
]
}
推荐答案
此错误来自规则 no-undef 。
如果变量未在范围内定义且不是已知的全局变量(如 Promise
,文档
等)。
This error comes from the rule no-undef.
Eslint will throw this error when a variable is not defined in scope and it's not a known global (like Promise
, document
, etc...).
您可以通过在要使用的文件中添加注释,将变量声明为全局变量,如下所示:
You can declare your variable as a global by putting a comment in the file you want to use it like this:
/ *全局todoEventBus * / $code>
或在您的声明中将其声明为全局变量eslint config
or you could declare it as a global in your eslint config
"eslintConfig": {
"globals": {
"todoEventBus": "readable"
}
}
这篇关于Vue | npm运行发球| ESLint全局变量未在组件内定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!