v-if指令
- v-if指令的作用是:根据表达式的真假切换元素的显示状态
- 本质是通过操纵dom元素来切换显示状态
- 表达式的值为true,元素存在于dom树中,为false,从dom树中移除
- 频繁的切换v-show,反之使用v-if,前者的切换消耗小
<input type="button" value="切换显示" @click="toggleIsShow">
<p v-if="isShow">v-if指令</p>
<p v-show="isShow">hei v-show修饰</p>
<h2 v-if="temperetrue>=35">热死了</h2>
data:{
isShow:false,
temperetrue:20
},
methods:{
toggleIsShow:function(){
this.isShow=!this.isShow;
}
v-bind指令
- v-bind指令的作用是:为元素绑定属性
- 完整写法是v-bind:属性名
- 简写可以直接省略v-bind,只保留 :属性名
- 需要动态的增删class建议使用对象的方式
<img :src="imgSrc" alt="" :title="imgTitle+'!!'" :class="{active:isActive} " @click="toggleActive">
实现图片切换
<div id='app'>
<img :src="imgArr[index]" alt="">
<a href="#" @click="prev" v-show="index!=0">上一张</a>
<a href="#" @click="next" v-show="index<imgArr.length-1">下一张</a>
</div>
data:{
imgArr:[
"./img/01.png",
"./img/02.png",
"./img/03.jpg",
"./img/04.jpg",
"./img/05.png",
],
index:0
},
methods:{
prev:function(){
this.index--;
},
next:function(){
this.index++;
}
- 列表数据使用数组保存
- v-bind指令可以设置元素属性,比如src
- v-show和v-if都可以切换元素的显示状态,频繁切换用v-show
v-for指令
- v-for指令的作用是:根据数据生成列表结构
- 数组经常和v-for结合使用
- 语法是{{item.index}} in 数据
- item和index可以结合其他指令一起使用
- 数据长度的更新会同步到页面上去,是响应式的
<input type="button" value="添加数据" @click="add">
<input type="button" value="移除数据" @click="remove">
<ul>
<li v-for="(item,i) in arr">
索引:{{i}} hello: {{item}}
</li>
</ul>
<h2 v-for="item in vegetables" v-bind:title="item.name">
{{item.name}}
</h2>
data: {
arr: [1, 2, 3, 4, 5],
vegetables:[
{name:"青菜"},
{name:"黄瓜"},
]
},
methods: {
add:function(){
this.vegetables.push({name:"番茄"});
},
remove:function(){
this.vegetables.shift();
}
v-on指令
- 事件绑定的方法写成函数调用的形式,可以传入自定义参数
- 定义方法时,需要定义形参来接收的实参
- 事件的后面跟上,修饰符可以对事件进行限制
- .enter可以限制触发的按键为回车
- 事件修饰符有很多种
<input type="button" value="点击" @click="doIt(66,'老铁')">
<input type="text" @keyup.enter="sayHi">
methods:{
doIt:function(p1,p2){
console.log("做IT");
console.log(p1);
console.log(p2);
},
sayHi:function(){
alert("吃了没");
}
v-model指令
- v-model指令的作用是便捷的设置和获取表单元素的值
- 绑定的数据会和表单元素值相关联
- 绑定的数据 <- -> 表单元素的值,双向绑定
<input type="button" value="修改msg" @click="setMsg">
<input type="text" v-model="msg" @keyup.enter="getMsg">
<h1>{{msg}}</h1>
data:{
msg:"v-model双向绑定"
},
methods:{
getMsg:function(){
alert(this.msg);
},
setMsg:function(){
this.msg="setMsg";
}
}