今天遇到一個問題,因為數據來源不是同一個數組,但是想使用連續的index。
簡化了一下,代碼長下面這樣,實際上第一眼看是沒有問題的。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>demo</title>
</head>
<body>
<div id="main">
<table>
<thead>
</thead>
<tbody>
<tr v-for="(item, index) in arr1">
<td >{{getIndex()}}</td>
</tr>
<tr v-for="(item, index) in arr2">
<td>{{getIndex()}}</td>
</tr>
</tbody>
</table>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
new Vue({
el: '#main',
data: {
arr1: [1, 2],
arr2: [3, 4, 5],
num:0
},
methods: {
getIndex: function () {
return ++this.num;
}
}
})
</script>
</body>
</html>
但是運行會有警告,並且顯示是不對的,因為渲染組件的時候,去改變了data里面的數據,data里面的數據變化又會調用render函數,從新渲染組件,這樣就造成了 死循環。
解決辦法:
1, computed屬性,將來源不同的數據合並到一個數組
2, 將totalIndex這個索引變量放全局變量里面