欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

Vue.js在数组中插入重复数据详解

程序员文章站 2022-04-10 16:03:23
...
本文主要介绍了Vue.js在数组中插入重复数据的实现代码,需要的朋友可以参考下,希望能帮助到大家。

1、在默认的情况下,Vue.js默认不支持往数组中加入重复的数据。可以使用track-by="$index"来实现。

2、不使用track-by="$index"的数组插入,数组不支持重复数据的插入

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代码

<p id="app"> 
   <!--显示数据--> 
   <ul> 
    <li v-for="value in arrMsg" > 
     {{value}} 
    </li> 
   </ul> 
   <button type="button" @click="add">增加数据</button> 
  </p>

2.2 结果

Vue.js在数组中插入重复数据详解

3、使用track-by="$index"的数组插入,数组支持重复数据的插入

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代码

<p id="app" class="container"> 
   <!--显示数据--> 
   <ul> 
    <li v-for="value in arrMsg" track-by="$index" > 
     {{value}} 
    </li> 
   </ul> 
   <button type="button" @click="add" >增加数据</button> 
  </p>

3.3 结果

Vue.js在数组中插入重复数据详解

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> 
  <p id="app" class="container"> 
   <!--显示数据--> 
   <ul> 
    <li v-for="value in arrMsg" track-by="$index" > 
     {{value}} 
    </li> 
   </ul> 
   <button type="button" @click="add" >增加数据</button> 
  </p> 
 </body> 
</html>

ps:下面看下vue 数组重复,循环报错

Vue.js默认不支持往数组中加入重复的数据。可以使用track-by="$index"来实现。

相关推荐:

Mysql删除重复数据保留最小的id

mysql查询表里的重复数据方法

php数组重复数据的处理

以上就是Vue.js在数组中插入重复数据详解的详细内容,更多请关注其它相关文章!