v-for遍歷陣列和物件
阿新 • • 發佈:2020-10-22
v-for最簡單的遍歷陣列
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="app"> <ul> <!-- v-for最基礎的陣列遍歷 --> <li v-for= 'i in names'>{{i}}</li> </ul> </div> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script> const app = new Vue({ el: '#app', data : { names : ['jack','mary','lucy','jerry'] } })</script> </body> </html>
如果需要索引(下標),新增index即可
<li v-for = '(i, index) in names'>{{index}}+{{i}}</li>
v-for遍歷物件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="app"> <ul> <li v-for= '(value,key) in info'>{{key}}----{{value}}</li> </ul> </div> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script> const app = new Vue({ el: '#app', data : { info : { name :'mary', age : 20, gender : 'female' } } }) </script> </body> </html>
也可以用index獲取下標,在物件的遍歷中比較少用