【问题标题】:Vue | npm run serve | ESLint global variable is not defined within a componentVue | npm 运行服务 | ESLint 全局变量未在组件内定义
【发布时间】:2020-02-23 00:57:55
【问题描述】:

我正在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"
  ]
}

【问题讨论】:

  • 使用 window.todoEventBus 或在 eslint 的已知全局变量中添加 todoEventBus

标签: javascript vue.js npm eslint


【解决方案1】:

此错误来自规则no-undef。 当变量未在作用域中定义并且它不是已知的全局变量(如Promisedocument 等)时,Eslint 将抛出此错误。

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

/* global todoEventBus */

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

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

【讨论】:

    【解决方案2】:

    修改 Alex 的回答,您还可以将规则具体缩小到 Vue SFC:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-26
      • 1970-01-01
      • 1970-01-01
      • 2015-08-22
      • 2021-07-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多