当前位置: 首页 > Web前端 > vue.js

Vue2.x学习笔记(三)

时间:2023-03-31 23:40:00 vue.js

1监控在Vue中,watch可以用来监控数据的变化,比如watch实现的一个简单的计数器:

Counter:{{count}}

点我添加

varvm=newVue({el:'#app',data:{count:0}})vm.$watch('count',function(newValue,oldValue){document.getElementById("info").innerHTML="修改前:"+oldValue+"
修改后:"+newValue;})效果如下:watch有两个参数,一个是要监听的变量,一个是回调函数,回调函数接受两个参数,第一个参数是新值,第二个参数为旧值。这是单位转换的另一个例子:吨:千克:
吨:

千克:

varvm=newVue({el:'#app',data:{ton:0,kgs:0},watch:{ton:function(val){this.kilograms=(this.ton=val)*1000;},kgs:function(val){this.ton=(this.千克=val)/1000;}}})vm.$watch('ton',function(newValue,oldValue){document.getElementById("tonInfo").innerHTML="修改前:"+oldValue+"
修改后修改:"+newValue;})vm.$watch('千克',function(newValue,oldValue){document.getElementById("kilogramsInfo").innerHTML="修改前:"+oldValue+"
修改后:"+新Value;})2stylebindingclass和style是HTML元素的属性,用来设置元素的样式,可以使用v-bind来设置样式属性v-bind是在处理class和style时特别增强的,结果expression类型除了可以是字符串,还可以是对象或数组。2.1类绑定可以为v-bind:class设置一个对象动态切换类:
vm=newVue({el:'#app',data:{isActive:true}})也可以传入多个属性动态切换多个类:.class0{width:100px;高度:100px;}.class1{背景:绿色;}.class2{背景:红色;varvm=newVue({el:'#app',data:{active1:true,active2:true}})效果:也可以用对象为了简化:varvm=newVue({el:'#app',数据:{类对象:{类1:true,class2:true}}})2.2计算属性v-bind:class中除了是一个对象,还可以绑定返回对象的计算属性,如:varvm=newVue({el:'#app',data:{active1:true,error:{value:true,type:'致命'}},计算:{classObject:function(){return{class0:true,class1:this.active1&&!this.error.value,class2:this.error.value&&this.error.type==='fatal'}}}})效果如下:2.3也可以传递一个数组给v-bind:class一个数组,数组的元素是变量,变量的内容是对应的CSS类名:varvm=newVue({el:'#app',data:{active1:'class0',active2:'class1'}})也可以用三元表达式来切换:3内联样式可以直接在v-bind:style中设置(注意前后的{}):测试varvm=newVue({el:'#app',data:{color:'#FF0000',fontSize:30}})当然也可以像绑定类一样直接绑定到一个对象上:testvarvm=newVue({el:'#app',data:{styleObject:{color:'#FF0000',fontSize:'30px'}}})数组也可以使用Bind多种样式:testvarvm=newVue({el:'#app',data:{styleObject1:{color:'#FF0000',},styleObject2:{fontSize:'30px'}}#5})另外,当v-bind:style需要有特殊前缀的CSS时,比如transform,Vue会自动检测并添加相应的前缀4事件处理4.1v-on事件监听可以使用v-on:点击增加1

这个按钮已被点击{{count}}次

varvm=newVue({el:'#app',data:{count:0}})通常点击一个按钮会触发一个方法调用,只需在方法中指定:点击触发事件varvm=newVue({el:'#app',methods:{test:function(){alert('Hello')//event表示是原生DOM事件if(event){alert(event.target.tagName)}}}})当然你也可以使用内部链接的Javascript语句:SayhiSaywhatvarvm=newVue({el:'#app',methods:{say:function(val){alert(val)}}})4.2事件修饰符Vue提供了事件修饰符供v-on处理DOM事件细节,如event.preventDefault()或event.stopPropagation(),通过.stop代表的指令调用修饰符:防止事件冒泡。prevent:提交事件不再重载页面,如.capture:事件捕获方式。self:仅当事件在元素本身(而不是子元素)上触发时回调。once:事件只能点击一次4.3Button修饰符Vue允许在v-on监听键盘事件时添加按键修改提示:keyCode值对应ASCII表,为了方便,Vue为常用键提供了别名:.esc.delete(删除+退格).enter/.space/.tab.up/.down/。left/.right.ctrl/.alt/当然.shift/.meta也可以结合按键,用.connect就可以了示例如下:

varvm=newVue({el:'#app',methods:{spacePressed:function(){document.getElementById("info").innerHTML="Youpressedspace";},ctrlCPressed:function(){document.getElementById("info").innerHTML="YoupressedCtrl+C";}}})