Vue2 使用插件 Volar 报错:<template v-for> key should be placed on the <template> tag.

  • A+
所属分类:Web前端
摘要

在 VS Code 上使用插件 Volar 开发 Vue3 项目,
然后去改 Vue2 项目时,对没有放在<template v-for>元素上的:key,会提示<template v-for> key should be placed on the <template> tag.


问题描述

在 VS Code 上使用插件 Volar 开发 Vue3 项目,
然后去改 Vue2 项目时,对没有放在<template v-for>元素上的:key,会提示<template v-for> key should be placed on the <template> tag.

原先 Vue2 项目开发时使用插件 Vuter。

Vue2 代码示例

<template v-for="(item, index) in list">   <div :key="index" /> </template> 

版本描述

Vue2 项目 Vue3 项目
[email protected] [email protected]
[email protected] [email protected]
[email protected] [email protected]
[email protected] [email protected]

问题定位

eslint-plugin-vue 规则上关于key是否能置于<template v-for>上的冲突

Priority A: Essential for Vue.js 2.x
规则vue/no-v-for-template-key: Disallow key attribute on <template v-for>
Priority A: Essential for Vue.js 3.x
规则vue/no-v-for-template-key-on-child: Disallow key of <template v-for> placed on child elements

上面这两个规则都是从版本 7.0.0 才开始加入

? Version
This rule was introduced in eslint-plugin-vue v7.0.0

Vue2 项目使用的 [email protected] 的文档仅有关于key能否置于<template>上的规则约束。

disallow key attribute on <template> (vue/no-template-key)

该规则从版本 3.4.0 开始加入

? Version
This rule was introduced in eslint-plugin-vue v3.4.0

可见 [email protected] 的 vue/no-template-key 约束了 key 的位置,不得放在<template>上。

旧的 Vue2 项目的key并没有放在<template>上却报错:<template v-for> key should be placed on the <template> tag.,可以看出是被当成 Vue3 来检查了。

这个提示属于 eslint-plugin-vue v7.0.0 版本及以上的规范,项目里的 eslint-plugin-vue 版本是 4.7.1,版本 7.0.0 的规范为什么会出现在这,还待查询......

猜测是由于插件 Volar 未配置支持 Vue2 模板。


问题解决

  1. 禁用插件 Vuter,使用插件 Volar;
    Vue3 文档建议使用 Volar,配置好后就可只使用 Volar 同时开发 Vue2 & Vue3,而使用 Volar 需要禁用 Vuter:

    You need to disable Vetur to avoid conflicts.

  2. 在项目根目录增加文件 jsconfig.json,文件内容如下
{   "vueCompilerOptions": {     "experimentalCompatMode": 2   }, } 

以上解决方法参考的是 Volar 关于 tsconfig.json 的设置

Using
Setup for Vue 2
3.Support Vue 2 template
Volar preferentially supports Vue 3. Vue 3 and Vue 2 template has some different. You need to set the experimentalCompatMode option to support Vue 2 template.

// tsconfig.json {   "compilerOptions": {     ...   },   "vueCompilerOptions": {     "experimentalCompatMode": 2   }, } 

我也不知道为什么这样是成功的,Vuter 文档有提及 jsconfig.json 的配置,Volar 文档仅提及了 tsconfig.json 的配置,就想着试下,就正常了


VS Code 插件地址

Vuter [Vue2 项目使用的插件]
Volar [Vue3 项目使用的插件]