vue2/3 里的 template 的 key 设置

作者: , 共 1909 字 , 共阅读 0

最近写一个 vue 的写法:

<template v-for="n in 10">
    <td>{{ 2 * n }} </td>
    <td>{{ 2 * n + 1 }} </td>
</template>

eslint 提示错误:

error  Elements in iteration expect to have 'v-bind:key' directives  vue/require-v-for-key
error  Elements in iteration expect to have 'v-bind:key' directives  vue/require-v-for-key

给元素加上key

<template v-for="n in 10">
    <td :key="2*n" >{{ 2 * n }} </td>
    <td :key="2*n+1" >{{ 2 * n + 1 }} </td>
</template>

eslint 提示错误:

VueCompilerError: <template v-for> key should be placed on the <template> tag.

template加上key

<template v-for="n in 10 " :key="n" >
    <td >{{ 2 * n }} </td>
    <td >{{ 2 * n + 1 }} </td>
</template>

eslint 提示错误:

error  '<template v-for>' cannot be keyed. Place the key on real elements instead  vue/no-v-for-template-key

所以怎么折腾都会有错。查了一下,对于这种 v-for template , vue2 和 vue3 有不同的处理要求:

  • Vue2 要求对实际节点也就是 template 内部节点设置 key。
  • Vue3 要求直接对 template 设置 key。

显然 eslint 同时检查了这两种要求,所以不管怎么着都会出错。

如果是 Vue3 项目,可强行忽略 v-for-template-key 检查:

{
  "name": "my-vue2-app",
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/essential",
      "eslint:recommended"
    ],
    "parserOptions": {
      "parser": "babel-eslint"
    },
    "rules": {
        "no-unused-vars": ["error", { 
            "varsIgnorePattern": "^_", 
            "argsIgnorePattern": "^_" }],
        "vue/no-v-for-template-key": ["off"]
    },
    "globals": {
        "$": true
    }
  }
}

Q. E. D.

类似文章:
在写代码过程中,会定义一些变量但没有用,比如为了保持函数参数原型:
相似度: 0.239
IT » javascript, vue
写项目的时候遇到有需要就往 package.json里面添加新的包,即使后面没用也忘了删除,结果越积累越多。depcheck是检查依赖项的工具,会提示哪些包没有实际用到。安装:
IT » Highcharts, vue
标准版的 Highcharts 要想提供导出数据,可参考https://api.highcharts.com/highcharts/exporting.csv,核心是引入exporting.jsexport-data.js两个额外的 JS ,不需要做别的操作:
编程 » Matlab, 优化
最近做了些东西,用到了 Matlab 的优化工具箱, optimization toolbox。因为以前没用过这东西,今天把这个工具箱的帮助文档基本上翻了一遍。
bootstrap 是一个前端库,做一些常见的布局和效果,能省掉至少 95%的功夫。最近直接从 v4 升级到 v5 ,发现网页有些布局就乱掉了。这里是调整笔记。
相似度: 0.081
投资 » 债券学院, 基点
我在前面债券的敏感性里简单介绍过债券的 DV01 ,即俗称的基点价值。那篇文章还不够完整,我这里再补充一下。
编程 » SQL
现在 Access 用的人应该不多了,本来我以为我也不可能用这玩意儿,但最近在用 VBA 通过 SQL 处理数据时,发现它的语法是 Access 的语法。平时对 SQL Server 语法相对熟悉一些。下文总结了 Access 和 SQL Server 语法的差异。
编程 » NaN, Python, Javascript, JSON
一般而言,在 Python 里:
该文为学习总结笔记。逐步完善中。
编程 » C++, 编译错误
在 gcc 中,存在继承关系的模版类,子类无法直接访问父类的成员,即使该成员是protectedpublic
在写代码过程中,会定义一些变量但没有用,比如为了保持函数参数原型:
最近经常看微信视频,有时候会被推送一些直播,然后看到下面这个下播请榜一吃饭的主播: