Vue入门教程 第四篇 (属性、事件)

computed计算属性

计算属性(computed)在处理一些复杂逻辑时是很有用的。它的定义方式与methods类似。

 1 <div id="app">
 2   <div>
 3     name:{{name}}
 4   </div>
 5   {{reversedMessage}}
 6 </div>
 7  
 8 <script>
 9 var vm = new Vue({
10   el: '#app',
11   data: {
12     name: 'Jimmy'
13   },
14   computed: {
15     // 计算属性的 getter
16     reversedMessage: function () {
17       return this.name+" welcome!"
18     }
19   }
20 })
21 </script>

执行结果:

 

我们可以使用 methods 来替代 computed,效果上两个都是一样的,但是 computed 是基于它的依赖缓存,只有相关依赖发生改变时才会重新取值。而使用 methods ,在重新渲染的时候,函数总会重新调用执行。

watch监听属性

可以通过 watch 来响应数据的变化。

范例:

 1 <div id = "computed_props">
 2     正方形边长 : <input type = "text" v-model = "length">
 3     正方形周长 : <input type = "text" v-model = "perimeter">
 4 </div>
 5 <p id="info"></p>
 6 <script type = "text/javascript">
 7     var vm = new Vue({
 8     el: '#computed_props',
 9     data: {
10         length : 0,
11         perimeter:0
12     },
13     watch : {
14         length:function(val) {
15             this.length = val;
16             this.perimeter = this.length * 4
17         },
18         perimeter : function (val) {
19             this.perimeter = val;
20             this.length=this.perimeter/4
21         }
22     }
23     });
24 </script>

执行结果:

当操作边长或周长时,watch都会监控到值的变化从而计算出对应的值。 

v-on事件绑定

v-on可以为元素绑定事件,可以用@简写。

 1 <div id="app">
 2   <button v-on:click="showCount1">一号按钮</button>
 3   <button @click="showCount2">二号按钮</button>
 4 </div>
 5  
 6 <script>
 7 var app = new Vue({
 8   el: '#app',
 9   data: {
10     count1: 0,
11     count2: 0,
12   },
13   // 在 `methods` 对象中定义方法
14   methods: {
15    showCount1(){
16        this.count1++;
17        alert("一号按钮已经被点击了"+this.count1+"次");
18    },
19    showCount2(){
20        this.count2++;
21        alert("二号按钮已经被点击了"+this.count2+"次");
22    },
23   }
24 })
25 </script>

 

v-on的拓展

 1 <!-- 阻止单击事件冒泡 -->
 2 <a v-on:click.stop="doThis"></a>
 3 <!-- 提交事件不再重载页面 -->
 4 <form v-on:submit.prevent="onSubmit"></form>
 5 <!-- 修饰符可以串联  -->
 6 <a v-on:click.stop.prevent="doThat"></a>
 7 <!-- 只有修饰符 -->
 8 <form v-on:submit.prevent></form>
 9 <!-- 添加事件侦听器时使用事件捕获模式 -->
10 <div v-on:click.capture="doThis">...</div>
11 <!-- 只当事件在该元素本身(而不是子元素)触发时触发回调 -->
12 <div v-on:click.self="doThat">...</div>
13 
14 <!-- click 事件只能点击一次,2.1.4版本新增 -->
15 <a v-on:click.once="doThis"></a>

 

Vue 允许为 v-on 在监听键盘事件时添加按键修饰符:

1 <input v-on:keyup.enter="submit">
2 <!-- 缩写语法 -->
3 <input @keyup.enter="submit">

全部的按键别名:

  • .enter
  • .tab
  • .delete (捕获 "删除" 和 "退格" 键)
  • .esc
  • .space
  • .up
  • .down
  • .left
  • .right
  • .ctrl
  • .alt
  • .shift
  • .meta

 

posted @ 2019-10-16 11:07  Hi-Jimmy  阅读(517)  评论(0编辑  收藏  举报