watch-监视数据的变化(1)

//html准备

<div id="app">
  <label for="userName">用户名:</label>
  <input type="text" id="userName" v-model="userName">
  <span v-show="isError">用户名长度为 6~12 个字符</span>
</div>

// 监视的数据一定是data里的数据

data: {
  userName: '',
  isError: false
},

// 监视数据

watch: {
  // 只要监视的数据变化了,那么这个函数就会被调用
  userName(curVal, oldVal) {
    // curVal 表示最新值
    // oldVal 表示上一次的值
    if (curVal.length < 6 || curVal.length > 12) {
      this.isError = true
    } else {
      this.isError = false
   }
  }
 }
posted @ 2018-08-26 16:53  cecelingmeng  阅读(663)  评论(0编辑  收藏  举报