温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-09-21 09:16:25 来源:脚本之家 阅读:146 作者:Bwz_Learning 栏目:web开发

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  结果    

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

<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 结果     

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> 
  <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在数组中插入重复数据的实现代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对亿速云网站的支持!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI