VueJS 中的 v-for 的 List Rendering 是一個強大的功能,可以方便將 JSON 資料轉換成 html 內容。
例如以下資料是由 API 或其他 JS 產生的,要用來製作選單 ( 用 Javascript 來動態產生選單 )
items: [ {name: "選單1", href: "https://tree.rocks/"}, {name: "選單2", href: "https://www.apple.com/"}, {name: "選單3", href: "https://github.com/"} ]
那麼可以放入 Vue JS 中
new Vue( { el: '#tree', data: { items: [ {name: "選單1", href: "https://tree.rocks/"}, {name: "選單2", href: "https://www.apple.com/"}, {name: "選單3", href: "https://github.com/"} ] } } );
在加點 html
<div id="tree"> <div class="menu_item" v-for="item in items" > <a v-bind:href="item.href" >{{ item.name }}</a> </div> </div>
就可以生成網頁了 ( 如下圖 )
範例網頁:
https://jsfiddle.net/Seachaos/w8ygx1dy/