v-for和v-on的补充
v-for
根据数据生成列表结构;
数组经常和v-for结合使用;
语法是v-for=“(item,index) in 数据”
遍历对象格式:(value,key)或(value,key,index)
item和index可以结合其他指令一起使用;
数组长度的更新会同步到页面上,是响应式的。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>v-for指令</title>
</head>
<body>
<div id="app">
<input type="button" value="添加" @click="add">
<input type="button" value="删除" @click="reduce">
<ul>
<li v-for="(item,index) in arr">
{{index+1}}我要在{{item}}买房
</li>
</ul>
<h2 v-for="item in foods" :title="item.name">
{{item.name}}
</h2>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<script>
var app = new Vue({
el:"#app",
data:{
arr:["北京","上海","杭州","郑州"],
foods:[{name:"西红柿鸡蛋"},
{name:"西兰花"}]
},
methods:{
add:function(){
this.foods.push({name:"西红柿"});
},
reduce:function(){
this.foods.shift();
}
}
})
</script>
</body>
</html>
v-on补充
- 事件绑定的方法写成函数调用的形式,可以传入自定义参数。
- 定义方法时需要定义形参来接收传入的实参。
- 事件的后面跟上.修饰符可以对事件进行限制
- .enter可以限制触发的按键为回车
- 如果方法不需要额外的参数,那么方法后的()可以不添加。但是注意:如果方法本身中有一个参数,那么默认将原生事件event参数传递进去。
- 如果需要同时传入某个参数,同时需要浏览器参数的event对象时,可以通过$event传入事件。
1 | |
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!