1. 程式人生 > >Vue.js(13)- Watch監聽資料變化

Vue.js(13)- Watch監聽資料變化

watch 監聽的特點:監聽到某個資料的變化後,側重於做某件事情

  • 只要被監聽的資料發生了變化,會自動觸發 watch 中指定的處理函式;

app.vue

<template>
  <div>
    <p>姓名:<input type="text" v-model="username"></p>
    <p>密碼:<input type="text" v-model="password" ref="pwdDOM"></p>
    <button>登入</button
> </div> </template> <script> export default { data() { return { username: '', password: '' } }, // 進行資料的監聽 watch: { password: function(newVal, oldVal) { if (newVal.length < 8) { // 設定紅色文字 this.$refs.pwdDOM.style.color = 'red
' } else { // 設定藍色文字 this.$refs.pwdDOM.style.color = 'blue' } } } } </script>

index.js

import Vue from 'vue'

import app from './app.vue'
const vm = new Vue({
  el: '#app',
  render: c => c(app)
})