一、v-for 的用法
循环指令,可以遍历 Number、String、Object、Array;
- 循环数字、字符串:有2个参数,分别是value和索引值;
循环对象:有3个参数,分别是 属性值、属性名、索引值;
- 循环数组对象:有2个参数,分别是 对象和索引值;
索引值和属性名可以省略不写。
<h4>遍历数字:</h4>
<div v-for="(value,idx) in forData1">
<span>值{{value}} --- 索引值{{idx}}</span>
</div>
<h4>遍历字符串:</h4>
<div v-for="(value,idx) in forData2">
<span>值{{value}} --- 索引值{{idx}}</span>
</div>
<h4>遍历对象:</h4>
<div v-for="(item,key,idx) in forData3">
<span>属性值{{item}} --- 属性名{{key}} --- 索引值{{idx}}</span>
</div>
<h4>遍历数组对象(嵌套循环):</h4>
<div v-for="(item,idx) in forData4" >
<span>对象{{item}} --- 索引值{{idx}}</span>
<div v-for="(i,key) in item">
<span>{{i}}---{{key}}</span>
</div>
</div> new Vue({
el: '#app',
data: {
forData1:3,
forData2:'abcd',
forData3:{name:'xixi',age:18},
forData4:[{name:'张飞',age:38},{name:'武松',age:48}]
}
})
运行结果:
二、v-bind绑定class的几种写法
绑定属性;
缩写: v-bind:class=" " ---> :class=" "
1. 常见写法
<div :class="classA"></div>
2. 数组语法
<div :class="[classA,classB]"></div>
3. 对象语法(绑定布尔值、属性,当判断条件比较复杂可以绑定方法)
<div :class="{'redFont':true,'blueBorder':ifhasBorder,'bigSize':changeSize()}"></div>
vue实例化配置:
<script src="./vue.js"></script>
<script>
var vm = new Vue({
el: '#app',
data: {
classA:'redFont',
classB:'blueBorder',
ifhasBorder:false
},
methods:{
changeSize:function(){
return false;
}
}
})
</script>
运行结果:
三、简单应用:tab标签切换
结合 v-for 、v-bind 以及 v-show 指令,实现简单的tab标签和内容同步切换,(样式引用bootstrap.css)。
<!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>Document</title>
<link rel="stylesheet" href="./bootstrap.css">
</head>
<body>
<div id="app">
<ul class="nav nav-tabs">
<li class="nav-item" v-for="(item,idx) in tabs">
<a :class="{'nav-link':true,active:idx===activeIndex}" href="#" @click="changeIdx(idx)">{{item}}</a>
</li>
</ul>
<div v-for="(item,idx) in contents">
<div v-show="idx===activeIndex" style="padding:10px;">{{item}}</div>
</div>
</div>
<script src="./vue.js"></script>
<script>
var vm = new Vue({
el: '#app',
data: {
tabs: ["水果", "玩具", "人名"],
contents: ['西瓜葡萄大苹果', '积木拼图小火车', '大雄小熊小小明'],
activeIndex:0
},
methods:{
changeIdx:function(idx){
this.activeIndex = idx;
}
}
})
</script>
</body>
</html>
运行结果: