Vue.js在數(shù)組中插入重復(fù)數(shù)據(jù)的實現(xiàn)代碼
1、在默認的情況下,Vue.js默認不支持往數(shù)組中加入重復(fù)的數(shù)據(jù)??梢允褂?code>track-by="$index"來實現(xiàn)。
2、不使用track-by="$index"的數(shù)組插入,數(shù)組不支持重復(fù)數(shù)據(jù)的插入
2.1 JavaScript代碼
<script type="text/javascript" src="../js/vue-1.0.21.js"></script>
<script type="text/javascript">
window.onload = function() {
vm = new Vue({
el: '#app',
data: {
arrMsg: ['apple', 'orage', 'pear']
},
methods: {
add: function() {
this.arrMsg.push('tamota');
}
}
});
}
</script>
2.2 html代碼
<div id="app">
<!--顯示數(shù)據(jù)-->
<ul>
<li v-for="value in arrMsg" >
{{value}}
</li>
</ul>
<button type="button" @click="add">增加數(shù)據(jù)</button>
</div>
2.2 結(jié)果
3、使用track-by="$index"的數(shù)組插入,數(shù)組支持重復(fù)數(shù)據(jù)的插入
3.1 Javascript代碼
<script type="text/javascript" src="../js/vue-1.0.21.js"></script>
<script type="text/javascript">
window.onload = function() {
vm = new Vue({
el: '#app',
data: {
arrMsg: ['apple', 'orage', 'pear']
},
methods: {
add: function() {
this.arrMsg.push('tamota');
}
}
});
}
</script>
3.2 html代碼
<div id="app" class="container">
<!--顯示數(shù)據(jù)-->
<ul>
<li v-for="value in arrMsg" track-by="$index" >
{{value}}
</li>
</ul>
<button type="button" @click="add" >增加數(shù)據(jù)</button>
</div>
3.3 結(jié)果

4、完整代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="../css/bootstrap.min.css" rel="external nofollow" />
<style type="text/css">
.container{
margin-top: 20px;
}
</style>
<script type="text/javascript" src="../js/vue-1.0.21.js"></script>
<script type="text/javascript">
window.onload = function() {
vm = new Vue({
el: '#app',
data: {
arrMsg: ['apple', 'orage', 'pear']
},
methods: {
add: function() {
this.arrMsg.push('tamota');
}
}
});
}
</script>
</head>
<body>
<div id="app" class="container">
<!--顯示數(shù)據(jù)-->
<ul>
<li v-for="value in arrMsg" track-by="$index" >
{{value}}
</li>
</ul>
<button type="button" @click="add" >增加數(shù)據(jù)</button>
</div>
</body>
</html>
ps:下面看下vue 數(shù)組重復(fù),循環(huán)報錯
Vue.js默認不支持往數(shù)組中加入重復(fù)的數(shù)據(jù)。可以使用track-by="$index"來實現(xiàn)。
總結(jié)
以上所述是小編給大家介紹的Vue.js在數(shù)組中插入重復(fù)數(shù)據(jù)的實現(xiàn)代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關(guān)文章
Vue.js中Line第三方登錄api的實現(xiàn)代碼
這篇文章主要介紹了Vue.js中Line第三方登錄api實現(xiàn)代碼,本文通過圖文并茂的形式給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-06-06
vue對象或者數(shù)組中數(shù)據(jù)變化但是視圖沒有更新問題及解決
這篇文章主要介紹了vue對象或者數(shù)組中數(shù)據(jù)變化但是視圖沒有更新問題及解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-07-07
Vue?3?使用moment設(shè)置顯示時間格式的問題及解決方法
在Vue?3中,因為過濾器(filter)已經(jīng)被廢棄,取而代之的是全局方法(global?method),本文給大家介紹Vue?3?使用moment設(shè)置顯示時間格式的問題及解決方法,感興趣的朋友一起看看吧2023-12-12

