VUE列表顺序错乱的问题(template在循环中的使用)

前言

页面渲染的和数据不一致,可以从两个方面排查。

  1. 看一下vue devtools的数据是否和预期的数据一致,如果不一致则是因为数据对象和之前不是一个对象了。
  2. 如果数据也一样,但顺序还不一样,就是渲染的问题。

顺序错乱

下面说一种渲染问题:

如果我们循环生成的是template,而其中的组件都使用v-if,这样渲染出来的顺序就和数据本身的顺序不一样。

错误的方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<template v-for="(item, index) in eleProps.children">
<form-comp-input
v-if="item.name === 'tpl_comp_input'"
:key="index"
class="flex1"
:ele-props="item"
/>
<form-comp-textarea
v-if="item.name === 'tpl_comp_textarea'"
:key="index"
class="flex1"
:ele-props="item"
/>
</template>

解决的方式很简单:

后续的用v-else-if即可。

正确的方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<template v-for="(item, index) in eleProps.children">
<form-comp-input
v-if="item.name === 'tpl_comp_input'"
:key="index"
class="flex1"
:ele-props="item"
/>
<form-comp-textarea
v-else-if="item.name === 'tpl_comp_textarea'"
:key="index"
class="flex1"
:ele-props="item"
/>
</template>

v-for和v-if

v-forv-if不建议在同一个元素上使用,一般要这样处理的时候,我们可以把v-for放在template上。

使用template的时候,key要绑定在子元素上。

并且如果有多个子元素,不要都用v-if,会导致渲染顺序问题。

下面是使用 <template> 元素包裹 v-if 和 v-for 的示例代码:

1
2
3
4
5
<template v-for="(item,index) in items">
<div v-if="item.condition" :key="index">
<!-- 根据条件渲染的内容 -->
</div>
</template>

通过使用 <template> 元素,可以解决 v-ifv-for 同时使用时的渲染顺序问题。

v-for 在 <template> 元素上进行迭代,而每次迭代时<div>元素根据条件进行渲染。

这种方式能够保持代码的可读性和维护性,并且不会引起意外的结果。

同时,还可以利用 <template> 元素的特性,避免不必要的 DOM 元素渲染,提升性能。