视图 | npm 运行 服务 | ESLint 全局变量未在组件内定义

Vue | npm run serve | ESLint global variable is not defined within a component

我在 main.js 中的 window 上设置一个 vue 实例,如下所示:

window.todoEventBus = new Vue()

在我的组件中,我试图像这样访问这个 todoEventBus 全局对象:

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 对象。

我的 package.json 文件如下所示。

{
  "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。 当变量未在范围内定义并且不是已知的全局变量(如 Promisedocument 等...)时,Eslint 将抛出此错误。

您可以通过在要使用它的文件中添加注释来将您的变量声明为全局变量:

/* global todoEventBus */

或者您可以在您的 eslint 配置中将其声明为全局变量

"eslintConfig": {
    "globals": {
        "todoEventBus": "readable"
    }
}

修改Alex的回答,你也可以将规则缩小到Vue SFC:

// .eslintrc.js

module.exports = {
    ...
    overrides: [
        {
            files: "*.vue",
            globals: {
                todoEventBus: "readable",
            },
        },
    ],
}