列表渲染
v-if+v-for+v-else控制购物车商品的显示
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>v-if + v-for + v-else控制购物车商品的显示title>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js">script>
<style>
table, td {
border: 1px solid black;
text-align: center;
}
style>
head>
<body>
<div id="box">
<h2>我的购物车h2>
<button @click="show">刷新购物车button>
<br><br>
<table v-if="!shopping_car.length==0">
<tr>
<td>商品名称td>
<td>价格td>
tr>
<tr v-for="item in shopping_car">
<td>{{item.name}}td>
<td>{{item.price}}td>
tr>
table>
<table v-else>
<tr>
<td>商品名称td>
<td>价格td>
tr>
<tr>
<td>暂无信息td>
<td>暂无信息td>
tr>
table>
div>
body>
<script>
let vm = new Vue({
el: '#box',
data: {
isActive: false,
shopping_car: []
},
methods: {
show() {
this.shopping_car = [
{name: 'Threadripper 3990X', price: '29999元'},
{name: 'NVIDIA RTX 8000', price: '59999元'},
{name: 'ROG ZENITH II EXTREME', price: '9999元'},
]
}
}
})
script>
html>

v-for遍历数组(列表)、对象(字典)、数字
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>v-for遍历数组(列表)、对象(字典)title>
<script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js">script>
<style>
table, td {
border: 1px solid black;
text-align: center;
}
style>
head>
<body>
<div id="box">
<h2>数组(列表)for循环遍历h2>
<ul>
<li v-for="(value,index) in list_test">{{index}} —— {{value}}li>
ul>
<h2>对象(字典)for循环遍历h2>
<ul>
<li v-for="(value,key) in dic_test">{{key}} —— {{value}}li>
ul>
<h2>数组(列表)套对象(字典)for循环遍历h2>
<table>
<tr>
<td>姓名td>
<td>年龄td>
<td>性别td>
<td>国籍td>
tr>
<tr v-for="info in summary_test">
<td>{{info.name}}td>
<td>{{info.age}}td>
<td>{{info.gender}}td>
<td>{{info.country}}td>
tr>
table>
div>
body>
<script>
let vm = new Vue({
el: '#box',
data: {
list_test: ['First', 'second', 'Third', 'Forth', 'Fifth'],
dic_test:{name: 'Darker', age: 18, gender: 'male'},
summary_test: [
{name: 'Alan', age: 23, gender: 'male', country: 'America'},
{name: 'Ben', age: 15, gender: 'male', country: 'Australia'},
{name: 'Cindy', age: 12, gender: 'female', country: 'Japan'},
{name: 'Darker', age: 18, gender: 'male', country: 'China'},
{name: 'Elisa', age: 26, gender: 'female', country: 'Mexico'},
]
}
})
script>
html>

注意:在Vue中
数组的index和value是反的
对象的key和value也是反的
key值的解释
看到被人代码在循环时,写在标签中 :key='值'
key:一般咱么在循环的时候,都要加 :key='值',值不要是固定的
vue中使用的是虚拟DOM,会和原生的DOM进行比较,然后进行数据的更新,提高数据的刷新速度(虚拟DOM用了diff算法)
在v-for循环数组、对象时,建议在控件/组件/标签写1个key属性,属性值唯一
页面更新之后,会加速DOM的替换(渲染)
:key="变量"
key可以加速页面的替换--key加上,效率高
数组更新与检测
可以检测到变动的数组操作:
push:最后位置添加
pop:最后位置删除
shift:第一个位置删除
unshift:第一个位置添加
splice:切片
sort:排序
reverse:反转
检测不到变动的数组操作:
filter():过滤
concat():追加另一个数组
slice():
map():
原因:作者重写了相关方法(只重写了一部分方法,但是还有另一部分没有重写)
解决方法:
// 方法1:通过 索引值 更新数组(数据会更新,但是页面不会发生改变)
vm.arrayList[0]
"Alan"
vm.arrayList[0]='Darker'
"Darker"
// 方法2:通过 Vue.set(对象, index/key, value) 更新数组(数据会更新,页面也会发生改变)
Vue.set(vm.arrayList, 0, 'Darker')