上海免费做网站做网站纸张大小
目录
问题描述
版本描述
问题定位
问题解决
VS Code 插件地址
问题描述
        在 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 项目 | 
|---|---|
| vue@2.6.14 | vue@3.2.19 | 
| eslint@4.19.1 | eslint@6.8.0 | 
| eslint-plugin-vue@4.7.1 | eslint-plugin-vue@7.18.0 | 
| babel-eslint@8.2.6 | babel-eslint@10.1.0 | 
问题定位
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 项目使用的 eslint-plugin-vue@4.7.1 的文档仅有关于
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可见 eslint-plugin-vue@4.7.1 的 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 模板。
问题解决
-  
禁用插件 Vetur,使用插件 Volar;
Vue3 文档建议使用 Volar,配置好后就可只使用 Volar 同时开发 Vue2 & Vue3,而使用 Volar 需要禁用 Vuter:You need to disable Vetur to avoid conflicts.
 -  
在项目根目录增加文件 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 的配置,就想着试下,就正常了
