% l: T! R6 @* u- H4 n5 j
本章节,我们将为大家介绍 Vue.js 监听属性 watch,我们可以通过 watch 来响应数据的变化: 实例
* M9 r$ B# u0 e# C% d; t* }
6 P/ ~9 H) `% a. ~" b, D- <div id = "computed_props">1 f4 x# l+ a" B E0 l
- 千米 : <input type = "text" v-model = "kilometers">
, U6 g( z5 M0 e4 t3 r - 米 : <input type = "text" v-model = "meters">; J+ B2 J% t7 m8 M- g# ~! {. O
- </div>7 M2 S5 {" g2 U p2 @' P+ H& V: M
- <p id="info"></p>0 m7 M3 \; r- {3 y: D
- <script type = "text/javascript">8 ?1 b2 B, Y2 V. o# [: H- ?
- var vm = new Vue({
! O6 ^" K4 u* Z. ? - el: '#computed_props',
; E" s6 l) V$ h; u9 X - data: {
+ c5 r: ?' [6 t( _- ~0 E/ M - kilometers : 0, x3 c# |0 I, B- B$ L: F: o+ ~: I
- meters:06 H5 `5 ]+ F: M* `$ E
- },
4 } S- _- [) b! F& I9 S9 K - methods: {
: [1 f1 P: Z+ |9 j - },
' A* N% T$ S' h* P! e5 K' n* \ - computed :{1 S4 A# t/ w4 f
- },- C& o* h% U) Q. r- Y
- watch : {
2 h% ?, W9 V9 r4 H - kilometers:function(val) {; x+ M5 A- {& Q$ M( J9 W2 R- u
- this.kilometers = val;
+ ~9 k: r m* I - this.meters = val * 1000;6 P7 @* S6 R4 Q' l( F$ j
- },
: Y$ p$ U! |) y1 O% a3 w0 ~ - meters : function (val) {
# `. R4 f6 W$ }# n - this.kilometers = val/ 1000;' t* b4 U. |; V9 n
- this.meters = val;
) n, n6 G3 G% w: O. B5 G - }
" e, Z. Z: X/ C. J$ s% o, b' r - }
7 Y3 V+ L6 z: K" k - });
8 ^; M. y K% x! L1 [ - // $watch 是一个实例方法
8 q1 o1 a9 v- ]# r9 m/ G' N - vm.$watch('kilometers', function (newValue, oldValue) {
1 ]1 W% ^1 B. Q) n0 z7 j" V - // 这个回调将在 vm.kilometers 改变后调用
6 O- O6 V. C/ M# u/ R - document.getElementById ("info").innerHTML = "修改前值为: " + oldValue + ",修改后值为: " + newValue;+ K# @, l5 b9 X' H% `
- })3 |! ~3 z' l/ K
- </script>
复制代码以上代码中我们创建了两个输入框,data 属性中, kilometers 和 meters 初始值都为 0。watch 对象创建了两个方法 kilometers 和 meters。 当我们再输入框输入数据时,watch 会实时监听数据变化并改变自身的值。
! G$ q2 ^0 y+ n( L2 W+ I! v# H, M( e9 G) q- ?* z: Z% l" l
% t8 ?; S: |- O' h/ Y0 V1 H% R( s
9 x9 c2 g) ?+ K8 J
|