条件渲染
-
v-if 与 v-else
-
v-show
节点存在,只是设置了 display:none;
<body>
<div id="app">
<!-- v-show -->
<div v-show="false">Hello</div>
<!-- v-if -->
<div v-if="false">No</div>
<!-- v-else -->
<div v-if="n === 1">n = 1</div>
<div v-else-if="n === 2">n = 2</div>
<div v-else>else</div>
<!-- template不会影响结构 -->
<template v-if="true">
<h1>标题1</h1>
<h2>标题2</h2>
</template>
</div>
<script>
new Vue({
el: "#app",
data() {
return {
n : 1
}
}
})
</script>
</body>
循环
- 数组
- 对象
- 字符串
- 遍历指定次数
<body>
<div id="app">
<h2>遍历数组</h2>
<ul>
<!-- 遍历数组 -->
<li v-for="(person, index) of personList" :key="person.id">
{{index}} : {{person.name}} - {{person.age}}
</li>
</ul>
<h2>遍历对象</h2>
<ul>
<!-- 遍历对象 -->
<li v-for="(v, field) of car" :key="field">
{{field}} : {{v}}
</li>
</ul>
<h2>遍历字符串 </h2>
<ul>
<!-- 遍历字符串 -->
<li v-for="(c, index) of str" :key="index">
{{index}} : {{c}}
</li>
</ul>
<h2>遍历指定次数 </h2>
<ul>
<!-- 遍历指定次数 -->
<li v-for="(number, index) of 6" :key="index">
{{index}} : {{number}}
</li>
</ul>
</div>
<script>
new Vue({
el: "#app",
data() {
return {
personList:[
{id: '001', name: 'dylan', age: 18},
{id: '002',name: 'harry', age: 19},
{id: '003',name: 'ron', age: 20}
],
car:{
name: '奥迪',
price: 200000
},
str: "hello"
}
}
})
</script>
</body>
列表过滤
使用watch
监听输入,过滤表格,得到的结果渲染
<body>
<div id="app">
<h2>人员列表</h2>
<input type="text" placeholder="输入姓名" v-model="keyWord">
<ul>
<!-- 遍历数组 -->
<li v-for="(person, index) of filterList" :key="person.id">
{{index}} : {{person.name}} - {{person.age}}
</li>
</ul>
</div>
<script>
new Vue({
el: "#app",
data() {
return {
personList:[
{id: '001', name: 'dylan', age: 18},
{id: '002',name: 'harry', age: 19},
{id: '003',name: 'ron', age: 20}
],
filterList: [],
keyWord: ''
}
},
watch:{
keyWord:{
immediate: true,
handler(val){
this.filterList = this.personList.filter((p)=>{
return p.name.indexOf(val) !== -1;
});
}
}
}
})
</script>
</body>