問題描述
在 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 模板。
問題解決
-
禁用插件 Vuter,使用插件 Volar;
Vue3 文檔建議使用 Volar,配置好后就可只使用 Volar 同時開發 Vue2 & Vue3,而使用 Volar 需要禁用 Vuter: -
在項目根目錄增加文件 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 的配置,就想着試下,就正常了