当前位置: 移动技术网 > IT编程>脚本编程>vue.js > Vue.js在数组中插入重复数据的实现代码

Vue.js在数组中插入重复数据的实现代码

2017年12月08日  | 移动技术网IT编程  | 我要评论

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

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

      2.2  结果    

 

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

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

      3.3 结果     

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

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

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

总结

以上所述是小编给大家介绍的vue.js在数组中插入重复数据的实现代码,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网