vue指令可以分为:
●内容绑定,事件绑定
●显示切换,属性绑定
●列表循环,表单元素绑定
6.v-bind
用于设置元素属性
写法:v-bind属性名 //v-bind也可省略
最后以点击图片切换为例综合使用以上指令
首先分析:1.用一个数组装图片地址
2.点击箭头图片,数组的下标要有相应变化(@click)
3.左右两个箭头在首尾要有隐藏(用v-show)
分析完毕下面代码实现:
<!DOCTYPE html> <html lang ="en"> <head> <meta charset="UFT-8"> <meta name = "viewport" comtent ="width=device-width,initial-scale=1.0" > <meta http-equiv ="X-UA-Compatible" Content = "ie=edge"> <title>实例:点击切换图片</title> </head> <body> <div id="mask"> <div class="center"> <!--left arrow--> <a href="javascript:void(0)" v-show="index!=0" @click="prev" class="left" > <img src="./img/lear.jpg" alt="" height="200" > </a> <!--picture--> <img :src="imgArr[index]" alt=""/> <!--right arrow--> <a href="javascript:void(0)" v-show="index<imgArr.length-1" @click="next" class="right"> <img src="./img/riar.jpg" alt="" height="200"> </a> </div> </div> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script> var app = new Vue({ el:"#mask", data:{ imgArr:["./img/1.png", "./img/2.jpg", "./img/3.jpg", "./img/4.jpg", "./img/5.jpg", ], index:0 }, methods:{ prev:function(){ this.index--; }, next:function(){ this.index++; } } }) </script> </body> </html>
实现的结果如下:
写代码的时候不停的想花花,所以就用了他的照片做例子,如有不妥,删。
7.v-for
根据数据形成列表结构,并且经常和数组结合使用。
他的语法是(item, index)in数据 其中item代表哪一项 index代表索引 除了in均可修改
数组长度的更新会响应式同步到页面上
案例代码如下:
<!DOCTYPE html> <html lang ="en"> <head> <meta charset="UFT-8"> <meta name = "viewport" comtent ="width=device-width,initial-scale=1.0" > <meta http-equiv ="X-UA-Compatible" Content = "ie=edge"> <title>实例:点击切换图片</title> </head> <body> <div id="app"> <input type="button" value="点我增加一首歌" @click="add"> <input type="button" value="点我删除一首歌" @click="remove"> <ul> <li v-for="(it,index) in arr"> {{index+1}}火星三部曲:{{it}} </li> </ul> <h2 v-for="item in other" v-bind:title="item.name"> {{item.name}} </h2> </div> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> <script> var app = new Vue({ el:"#app", data:{ arr:["与火星的孩子对话","好像爱这个世界啊","疯人院"], other:[ {name:"神树"}, {name:"降临"} ] }, methods:{ add:function(){ this.other.push({name:"斗牛"}); }, remove:function(){ this.other.shift(); } }, }) </script> </body> </html>
注意看增加方法add与删除方法remove。 鼠标点一下就会出现一个“斗牛”效果图如下:
8.v-model
获取和设置表单元素的值。