/ Y" _. p* i4 z/ P
本章节,我们将为大家介绍 Vue.js 监听属性 watch,我们可以通过 watch 来响应数据的变化: 实例
9 V& A- d- k, I. j4 b4 D @; G# l- Y* V
- <div id = "computed_props">) J! k8 \# }6 H- E# A9 M
- 千米 : <input type = "text" v-model = "kilometers">
) ]/ a, @. u3 s2 a6 j - 米 : <input type = "text" v-model = "meters">, [% }) ~, y L+ S( j7 c
- </div>- e3 F. l2 \; o
- <p id="info"></p>
% K2 I8 G$ M2 x - <script type = "text/javascript">5 \3 O" d8 b" l: P' S7 | Q
- var vm = new Vue({% j, o! ?7 K+ c0 V. h
- el: '#computed_props',+ f( x, d! J& [; T( w$ m' c8 Q
- data: {
3 y( K5 d* z) f/ d' E* ` - kilometers : 0,2 ?' n6 [& g$ c' s9 r
- meters:08 }0 e# k( y% F0 v& x
- },8 }* @" f: z! S2 Z# {- y) M
- methods: {
4 y/ r% J& M* C' A - },
. U# Y d7 y4 t" Q - computed :{
9 o! h7 M: A/ {6 { - },! d) L! t, v/ _) w
- watch : {
T" Q2 f, W3 X! i7 Q1 `2 n - kilometers:function(val) {
* [ W5 W* ]1 |* P- d - this.kilometers = val;) V! U' ~" \' b0 r. C k8 A7 D
- this.meters = val * 1000;( Y' V, V6 ~' G% G% z2 R
- },
( K) g& w5 D/ q9 E, s9 E - meters : function (val) {: T B( \3 S) r( H! b
- this.kilometers = val/ 1000;
9 L+ i( `/ _; F% L( B! k - this.meters = val;
4 x9 I O+ {9 m7 C) ? - }
1 P) l& m# Y; L h - }7 Q* A) ?" f: ^1 y5 I, d/ y
- });% j$ E1 b( O9 s8 ]; i
- // $watch 是一个实例方法
" M1 \8 Z8 m. v) }4 F# Y" ~ - vm.$watch('kilometers', function (newValue, oldValue) {
2 V R1 C0 X* C: _" h - // 这个回调将在 vm.kilometers 改变后调用. O6 q2 X. U% H$ U. y" n
- document.getElementById ("info").innerHTML = "修改前值为: " + oldValue + ",修改后值为: " + newValue;8 K5 `( |$ a/ S3 t
- })9 j4 J- b0 h. K1 P' ]0 Z
- </script>
复制代码以上代码中我们创建了两个输入框,data 属性中, kilometers 和 meters 初始值都为 0。watch 对象创建了两个方法 kilometers 和 meters。 当我们再输入框输入数据时,watch 会实时监听数据变化并改变自身的值。
' I6 d5 Z: }* j% ]+ F0 I% z
4 Z- D5 r) d7 n' ^2 j% \. I* y3 R' p- ]! V2 c- O3 c- [
7 g! F. t8 B* N7 q
|