Vue | npm运行发球| ESLint全局变量未在组件内定义

时间:2019-10-27 12:27:58

标签: javascript vue.js npm eslint

我正在main.js的窗口中设置一个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"
  ]
}

2 个答案:

答案 0 :(得分:2)

错误来自规则no-undef。 如果变量没有在范围内定义并且不是已知的全局变量(例如Promisedocument等),则Eslint将产生此错误。

您可以通过在要使用的文件中添加注释,将变量声明为全局变量,如下所示:

/* global todoEventBus */

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

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

答案 1 :(得分:0)

根据Alex的回答,您还可以专门将规则缩小到Vue SFC:

// .eslintrc.js

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