参考书籍《Vue.js快跑:构建触手可及的高性能Web应用》第1章 Vue.js基础-----1-5模板中的循环(v-for)
另外一个我经常使用的指令是v-for,这个指令通过遍历一个数组或者对象,将指令所在的元素循环输出到页面上。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>模板中的循环</title> </head> <body> <div id="app"> <ul> <li v-for="book in books">{{book}}</li> </ul> </div> <script src="https://unpkg.com/vue"></script> <script> new Vue({ el: "#app", data: { path: location.pathname, books:["《茶馆》", "《龙须沟》", "《四世同堂》", "《骆驼祥子》"] } }) </script> </body> </html>
用来遍历对象:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>模板中的循环</title> </head> <body> <div id="app"> <ul> <li v-for="book in books">{{book.name}}的价格为:{{book.price}}元</li> </ul> </div> <script src="https://unpkg.com/vue"></script> <script> new Vue({ el: "#app", data: { path: location.pathname, books: [ { name: "《茶馆》", price: "10.20" }, { name: "《龙须沟》", price: "10.00" }, { name: "《四世同堂》", price: "5.25" }, { name: "《骆驼祥子》", price: "3.5" }] } }) </script> </body> </html>