Vue-条件渲染和列表渲染

Vue-条件渲染和列表渲染

条件渲染

v-if

v-if=”表达式/数据”

使用v-if属性来选择是否渲染该元素到Dom树中

当数据为true,则该元素被渲染到Dom树中


v-else

使用v-else对与之对应的v-if取反


v-show

使用v-show实现与v-if相同的效果

与v-if不同的是,即使v-show的值为false,也仍然将该元素渲染到Dom树中

通过css样式:style=”display: none” 来实现不显示在页面上,但该元素仍然被渲染

总的来说:v-if有更高的切换开销,v-show有更高的初始渲染开销


列表渲染

使用v-for遍历对象/数组,使其内容绑定列表项

v-for=”(item, index) in items” :key=”item.id”

其中,index为遍历时索引,item为遍历项

将v-for放到li/td上,将遍历数组/对象,在li/td中使用插值表达式访问内容

在vue中,需要告知其属性key,这个属性并不会被渲染,但在编辑器中不写会报红

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
<script setup>
import { reactive, ref } from "vue";

let pro = ref("产品");
let items = reactive([
{
id: "item1",
message: "薯片",
},
{
id: "item2",
message: "可乐",
},
{
id: "item3",
message: "炸鸡",
},
]);
</script>

<template>
<div>
<ul>
<li v-for="(item, index) in items" :key="item.id">
{{ pro }}{{ index + 1 }}{{ item.message }}
</li>
</ul>
</div>
</template>

<style scoped>
</style>

购物车练习

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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<script setup>
import { reactive } from "vue";
let carts = reactive([
{
name: "可乐",
price: 3,
number: 10,
},
{
name: "薯片",
price: 6,
number: 12,
},
{
name: "炸鸡",
price: 12,
number: 2,
},
]);

//购物车总金额功能
function compute() {
let total = 0;
for (let index in carts) {
total = total + carts[index].price * carts[index].number;
}
return total;
}

//购物车删除功能
function removeCart(index) {
carts.splice(index, 1);
}

//购物车一键清空功能
function clearCart(){
//调用API清除
carts.splice(0,carts.length)
}


</script>

<template>
<div>
<h1>您的购物车如下</h1>
<table border="1px">
<thead>
<tr>
<th>序号</th>
<th>名称</th>
<th>单价</th>
<th>数量</th>
<th>小计</th>
<th>操作</th>
</tr>
</thead>
<!-- 当购物车中有购物项时,展示这个tbody-->
<tbody v-if="carts.length > 0">
<tr v-for="(cart, index) in carts" :key="index">
<td>{{ index + 1 }}</td>
<td>{{ cart.name }}</td>
<td>{{ cart.price }}</td>
<td>{{ cart.number }}</td>
<td>{{ cart.number * cart.price }}</td>
<td>
<button @click="removeCart()">删除</button>
</td>
</tr>
</tbody>
<!-- 当购物车中没有购物项时,展示这个tbody-->
<tbody v-else>
<td colspan="6">购物车空啦</td>
</tbody>
</table>
<button @click="clearCart()">一键清空购物车</button>
购物车总金额:{{ compute() }}元
</div>
</template>

<style scoped>
</style>


Vue-条件渲染和列表渲染
http://blog.170827.xyz/2024/05/06/Vue-条件渲染和列表渲染/
作者
XIAOBAI
发布于
2024年5月6日
许可协议