本文實例講述了Vue指令v-for遍歷輸出JavaScript數組及json對象的常見方式。分享給大家供大家參考,具體如下:
定義數據:
<script>
new Vue({
el:"#test",
data:{
message:"infor",
list:["a","b","c","d","e"],
web:{
"百度":"https://www.baidu.com",
"搜狐":"https://www.sohu.com",
"新浪":"https://www.sina.com",
"淘寶":"https://www.taobao.com"
}
}
})
</script>
html結構:
<div id="test">
<div>{{ message }}</div>
<div>{{ list }}</div>
<div>{{ web }}</div>
</div>
完整示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>v-for遍歷</title>
</head>
<body>
<div id="test">
<div>{{ message }}</div>
<div>{{ list }}</div>
<div>{{ web }}</div>
</div>
<script src="https://cdn.bootcss.com/vue/2.4.4/vue.min.js"></script>
<script>
new Vue({
el:"#test",
data:{
message:"infor",
list:["a","b","c","d","e"],
web:{
"百度":"https://www.baidu.com",
"搜狐":"https://www.sohu.com",
"新浪":"https://www.sina.com",
"淘寶":"https://www.taobao.com"
}
}
})
</script>
</body>
</html>
使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.jb51.net/code/HtmlJsRun冊數,輸出結果:

v-for對數組的幾種輸出方式:
1.只輸出value值
html代碼:
<div id="test">
<div v-for = "item in list">{{ item }}</div>
</div>
使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.jb51.net/code/HtmlJsRun冊數,輸出結果:

2.輸出value值且輸出對應的索引值
html代碼:
<div id="test">
<div v-for = "(item,index) in list">{{ item }}的索引值是{{ index }}</div>
</div>
使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.jb51.net/code/HtmlJsRun冊數,輸出結果:

v-for對json格式的幾種輸出方式
1.只輸出value值
html代碼:
<div id="test">
<div v-for = "item in web">{{ item }}</div>
</div>
使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.jb51.net/code/HtmlJsRun冊數,輸出結果:

2.輸出value值和key值
html代碼:
<div id="test">
<div v-for = "(item,key) in web">{{ key }} 的網址是 : {{ item }}</div>
</div>
使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.jb51.net/code/HtmlJsRun冊數,輸出結果:

3.輸出value值,key值和索引值index
html代碼:
<div id="test">
<div v-for = "(item,key,index) in web">{{ index }}__{{ key }} 的網址是 : {{ item }}</div>
</div>
使用在線HTML/CSS/JavaScript代碼運行工具:http://tools.jb51.net/code/HtmlJsRun冊數,輸出結果:

可以看出,在數組里面,小括號里面的參數第一位是value值,第二位是索引值
在json里面,第一位是value值,第二位是key值,第三位是索引值
有的文章里面說$index是數組的內置變量數組下標,$key是json內置變量,可是我沒有測出來,且提示有錯,不知道這個到底對不對。
希望本文所述對大家vue.js程序設計有所幫助。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。