条件渲染: V-for:列表渲染、条件渲染: v-if和键盘修饰符
1. Vue V-for:列表渲染
<!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>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<div class="app">
<ul>
<li>{{cities[0]}}</li>
<li>{{cities[1]}}</li>
<li>{{cities[2]}}</li>
</ul>
<hr>
<!-- 数组渲染 -->
<!-- v-for指令快速循环输出列表 -->
<ul>
<!-- key:diff算法,实现高效的渲染,大数量时有用 -->
<li v-for="(city,key) of cities" :key="key">{{key}} : {{city}}</li>
</ul>
<hr>
<!-- 对象渲染 -->
<ul>
<li v-for="(item,key) of user" :key="key">{{key}} : {{item}}</li>
</ul>
<hr>
<!-- 对象渲染 -->
<ul>
<li v-for="(item,key) of users" :key="key"> {{item.name}} : {{item.email}} : {{item.phone}}</li>
</ul>
</div>
<script>
const app = Vue.createApp({
data() {
return {
// 数组类型
cities: ['合肥', '上海', '南京'],
// 对象类型
user: {
name:'老马',
email:'nx77@qq.com',
phone:'13909511100',
},
// 对象数组
users:[
{
name:'老马',
email:'nx77@qq.com',
phone:'13909511100',
},
{
name:'老李',
email:'nx88@qq.com',
phone:'13909511100',
},
{
name:'老王',
email:'nx77@qq.com',
phone:'13909511100',
},
]
};
},
});
const vm = app.mount('.app');
</script>
</head>
<body>
</body>
</html>
2. Vue 条件渲染: v-if
<!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-if</title>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div class="app">
<!-- v-if:条件渲染指令 -->
<p v-if="flag">{{message}}</p>
<!-- !取反操作 ,如:flag = !flag-->
<button @click="flag = !flag" v-text="flag ? '隐藏':'显示'"></button>
<!-- if-else,if elseif if -->
<!-- p >= 1000 and p < 2000 -->
<p v-if="point >= 1000 && point < 2000">{{grade[0]}}</p>
<p v-else-if="point >= 2000 && point < 3000">{{grade[1]}}</p>
<p v-else-if="point >= 3000 && point < 4000">{{grade[2]}}</p>
<p v-else>{{grade[3]}}</p>
</div>
<script>
Vue.createApp({
data() {
return {
message: '前端快结束了',
flag: true,
//会员plus级别
grade:['普通会员','高级会员','金牌会员','至尊会员'],
//积分
point:5000,
};
},
}).mount('.app');
</script>
</body>
</html>
3. Vue 键盘修饰符
<!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>键盘修饰符</title>
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
</head>
<body>
<div class="app">
<!-- @keyup.enter :Vue监听鼠标回车事件 -->
<input type="text" @keyup.enter="submit($event)">
<ul>
<li v-for="(item,key) of list">{{item}}</li>
</ul>
</div>
<script>
Vue.createApp({
data() {
return {
// 留言列表
list: [],
};
},
methods: {
submit(ev) {
// 将输入的字符串放入 list 数组
this.list.unshift(ev.target.value);
ev.target.value = null;
},
},
}).mount('.app');
</script>
</body>
</html>