vue3引入dataV 在main.js/ts引入后报VueCompilerError: <template v-for> key should be placed on the <template>
把template标签变为div,将v-for 和 key 放入div中,两个文件都要改,改完你会发现运行还报错;把项目关掉重新打开,记住是重新打开这个项目文件运行,而不是重新运行。
·
首先,报错文件为decoration6 和decoration3
报错的原因是:
需要为模板中的一级元素添加 key 属性。模板的一级元素为 div.dv-decoration-3,因此需要为这个 div 元素添加 key 属性,而不是为循环中的 rect 元素添加。
解决办法
我找了解决办法 1、可以通过添加 ref(如代码中的 :ref="ref")来实现为 div 元素添加 key 属性。ref 属性会在组件中创建一个唯一的标识符,可以用来引用组件实例。你可以将该标识符作为 key 属性的值,以保证每个循环中 div 元素都有一个唯一的 key。(并没有用)
2 把template标签变为div,将v-for 和 key 放入div中,两个文件都要改,改完你会发现运行还报错;把项目关掉重新打开,记住是重新打开这个项目文件运行,而不是重新运行。
改之后可以运行的代码如下:(两个文件都要改!)
<template>
<div class="dv-decoration-6" :ref="ref">
<svg :width="`${svgWH[0]}px`" :height="`${svgWH[1]}px`" :style="`transform:scale(${svgScale[0]},${svgScale[1]});`">
<div
v-for="(point, i) in points"
:key="i"
>
<rect
:fill="mergedColor[Math.random() > 0.5 ? 0 : 1]"
:x="point[0] - halfRectWidth"
:y="point[1] - heights[i] / 2"
:width="rectWidth"
:height="heights[i]"
>
<animate
attributeName="y"
:values="`${point[1] - minHeights[i] / 2};${point[1] - heights[i] / 2};${point[1] - minHeights[i] / 2}`"
:dur="`${randoms[i]}s`"
keyTimes="0;0.5;1"
calcMode="spline"
keySplines="0.42,0,0.58,1;0.42,0,0.58,1"
begin="0s"
repeatCount="indefinite"
/>
<animate
attributeName="height"
:values="`${minHeights[i]};${heights[i]};${minHeights[i]}`"
:dur="`${randoms[i]}s`"
keyTimes="0;0.5;1"
calcMode="spline"
keySplines="0.42,0,0.58,1;0.42,0,0.58,1"
begin="0s"
repeatCount="indefinite"
/>
</rect>
</div>
</svg>
</div>
</template>
更多推荐
已为社区贡献1条内容
所有评论(0)