問題描述
在 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 模板,
問題解決
- 禁用插件 Vuter,使用插件 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 的配置,就想著試下,就正常了
VS Code 插件地址
Vuter [Vue2 專案使用的插件]
Volar [Vue3 專案使用的插件]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/347030.html
標籤:其他
