使用事件处理来做,用key up
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <input v-model="firstname" @keyup="getFullname" /> + <input v-model="lastname" @keyup="getFullname"/> = <input v-model="fullname" /> </div> <script type="text/javascript"> let vm=new Vue({ el:'#app', data:{ firstname:'', lastname:'', fullname:'' }, methods:{ getFullname(){ this.fullname=this.firstname+this.lastname; } } }); </script> </body> </html>
用function,注意区别,定义的属性,有get和set
fullname:{ get:function(){ return this.firstname+this.lastname; }, set:function(val){ let index=val.indexOf("-") this.firstname=val.substring(0,index); this.lastname=val.substring(index+1); } }
<script type="text/javascript"> let vm=new Vue({ el:'#app', data:{ firstname:'', lastname:'', }, methods:{ }, computed:{ //computed中定义的function,可以直接当做属性来使用 //当此function体中使用到的属性值发生改变,则重新执行function //computed会缓存执行的结果 fullname:function(){ return this.firstname+this.lastname; } } }); </script>
用watch监听,
<script type="text/javascript"> let vm=new Vue({ el:'#app', data:{ firstname:'', lastname:'', fullname:'' }, methods:{ }, watch:{ //watch中定义function,function的名字与data属性名一样 firstname:function(){ this.fullname=this.firstname+this.lastname; }, lastname:function(){ this.fullname=this.firstname+this.lastname; } } }); </script> 带参数 watch:{ //watch中定义function,function的名字与data属性名一样 firstname:function(newVal,oldVal){ this.fullname=newVal+this.lastname; }, lastname:function(newVal,oldVal){ this.fullname=this.firstname+oldVal; }, }
绑定路由切换跳转的时候运行的,要用watch
watch:{ "$route":function(newval,oldval) { alert(newval.path+" "+oldval.path); if(newval.path=="/login"){ alert("欢迎来到对抗路"); } } }
为什么要用vue,因为手动vue的搭建环境特别难,所有的文件,配置都需要自己弄,
compute
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <input v-model="firstname" /> + <input v-model="lastname" /> = <input v-model="fullname" /> <button type="button" @click="modify">111</button> </div> <script type="text/javascript"> let vm=new Vue({ el:'#app', data:{ firstname:'', lastname:'', }, methods:{ modify(){ this.fullname="12343-asd"; } }, computed:{ //computed中定义的function,可以直接当做属性来使用 //当此function体中使用到的属性值发生改变,则重新执行function fullname:{ get:function(){ return this.firstname+this.lastname; }, set:function(val){ let index=val.indexOf("-") this.firstname=val.substring(0,index); this.lastname=val.substring(index+1); } } } }); </script> </body> </html>
我们自己的写法
post