選單
×
   ❮   
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP 如何 W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AI GO KOTLIN SASS VUE DSA 生成式 AI SCIPY AWS 網路安全 資料科學
     ❯   

Vue 教程

Vue 首頁 Vue Intro Vue Directives Vue v-bind Vue v-if Vue v-show Vue v-for Vue Events Vue v-on Vue Methods Vue Event Modifiers Vue Forms Vue v-model Vue CSS Binding Vue Computed Properties Vue Watchers Vue Templates

Scaling Up

Vue 為什麼、如何及設定 Vue 首個 SFC 頁面 Vue 元件 Vue Props Vue v-for 元件 Vue $emit() Vue 穿透屬性 Vue 區域性作用域樣式 Vue 區域性元件 Vue 插槽 Vue v-slot Vue 區域性作用域插槽 Vue 動態元件 Vue Teleport Vue HTTP 請求 Vue 模板引用 Vue 生命週期鉤子 Vue Provide/Inject Vue 路由 Vue 表單輸入 Vue 動畫 Vue v-for 動畫 Vue 構建 Vue Composition API

Vue Reference

Vue Built-in Attributes Vue Built-in Components Vue Built-in Elements Vue Component Instance Vue Directives Vue Instance Options Vue Lifecycle Hooks

Vue 示例

Vue Examples Vue Exercises Vue Quiz Vue Server Vue Certificate

Vue $watch() 方法


示例

使用 $watch() 方法建立一個監聽器,每當 'value' 資料屬性改變時,它都會寫入一條新訊息。

mounted() {
  this.$watch('value', function() {
    this.results.push('$watch() method')
  })
}
執行示例 »

更多示例請參見下方。


定義和用法

$watch() 方法用於建立監聽器。

$watch() 方法返回一個停止函式,我們可以用它來停止監聽器。(參見示例 4

監聽器用於監視值的變化(第一個引數),並在發生變化時執行操作(第二個引數)。也可以為監聽器定義其他屬性(第三個引數)。

引數 描述
監聽源 必需。第一個引數是監聽源。這可以是一個元件屬性名稱字串(上面的示例),一個簡單的點分隔路徑字串(示例 5),或一個函式(示例 6)。
回撥函式 必需。第二個引數是一個回撥函式,當監聽源發生變化時執行。回撥函式可以設定為接收監聽源的新舊值作為引數(參見示例 1)。
選項物件 可選。在這裡我們可以指定 deep、immediate、flush 和 onTrigger/onTrack 選項。

deep: 預設值為 'false'。如果監聽器是深度監聽的,它還會對監聽器所設定的屬性內部更深層次的更改做出反應。(參見示例 2

immediate: 預設值為 'false'。在建立後立即觸發監聽器。當 'immediate' 設定為 'true' 時,監聽器首次觸發時,舊值將為 'undefined'。(參見示例 3

flush: 預設值為 'pre'。指定回撥函式相對於元件渲染何時執行。可能的值為 'pre'、'post' 和 'sync'。請謹慎使用此 flush 選項。

onTrigger/onTrack: 用於除錯。僅在開發模式下有效。

注意: 監聽器也可以使用 watch 選項建立。


更多示例

示例 1

使用 $watch() 方法,每當 'value' 資料屬性改變時,都會寫入一條包含新舊值的新訊息。

<template>
  <h2>Example $watch() Method</h2>
  <p>Drag the slider to change the value so that the $watch() method is triggered. The callback function writes a message with the new and old values.</p>
  <div>
    <p><input type="range" min="0" max="10" v-model="value"> Current value: {{ value }}</p>
    <ol>
      <li v-for="x in results">{{ x }}</li>
    </ol>
  </div>
</template>

<script>
export default {
  data() {
    return {
      value: 4,
      results: []
    };
  },
  mounted() {
    this.$watch('value', function(newVal, oldVal) {
      this.results.push('Old value:'+oldVal+', new value: '+newVal)
    })
  }
};
</script>

<style scoped>
div {
  border: solid black 1px;
  padding: 10px;
}
</style>
執行示例 »

示例 2

使用 $watch() 方法並將 deep 監聽選項設定為 'true'。現在,監聽器可以檢測到 'value' 物件內部更深層次的更改。

<template>
  <h2>Example $watch() Method</h2>
  <p>Register an extra hobby for Stuart. The hobbies are stored in an array inside the 'value' object. The $watch() method
    is triggered because the 'deep' option is set to 'true' so that the watcher also detects changes further inside the
    object.</p>
  <div>
    <p>Register an extra hobby for Stuart:</p>
    <p><input type="text" ref="inpText"></p>
    <button v-on:click="regHobby">Register</button>
    <ol>
      <li v-for="x in watchMessages">{{ x }}</li>
    </ol>
  </div>
  <p>Current 'value' object:</p>
  <pre>{{ this.value }}</pre>
</template>

<script>
export default {
  data() {
    return {
      value: {
        owner: 'Stuart',
        address: 'Faraway Lane',
        hobbies: ['Bird watching', 'Trail running']
      },
      watchMessages: []
    };
  },
  methods: {
    regHobby() {
      this.value.hobbies.push(this.$refs.inpText.value);
      this.$refs.inpText.value = null;
      this.$refs.inpText.focus();
    }
  },
  mounted() {
    this.$watch('value', function () {
      this.watchMessages.push('watcher triggered')
    }, {
      deep: true
    });
  }
};
</script>

<style scoped>
div {
  border: solid black 1px;
  padding: 10px;
}

li {
  background-color: lightgreen;
}</style>
執行示例 »

示例 3

使用 $watch() 方法並將 immediate 監聽選項設定為 'true'。現在,監聽器在建立後也會立即觸發。

<template>
  <h2>Example $watch() Method</h2>
  <p>With the 'immediate' option set to 'true' the watcher is also triggered right after it is created.</p>
  <div>
    <input type="range" min="0" max="10" v-model="value"> Current value: {{ value }}
    <p>Messages from the watcher:</p>
    <ol>
      <li v-for="x in watchMessages">{{ x }}</li>
    </ol>
  </div>
</template>

<script>
export default {
  data() {
    return {
      value: 4,
      watchMessages: []
    };
  },
  mounted() {
    this.$watch('value', (newVal, oldVal) => {
      this.watchMessages.push('Old value: '+oldVal+' New value: '+newVal)
    }, {
      immediate: true
    });
  }
};
</script>

<style scoped>
div {
  border: solid black 1px;
  padding: 10px;
}

li:first-child {
  background-color: lightgreen;
}</style>
執行示例 »

示例 4

使用 $watch() 方法返回的停止函式來停止監聽器。

<template>
  <h2>Example $watch() Method</h2>
  <p>Drag the slider to see the watcher work, click the stop button, and drag the slider again to confirm that the watcher has now stopped.</p>
  <div>
    <p><input type="range" min="0" max="10" v-model="value"> Current value: {{ value }}</p>
    <button v-on:click="stopFunc">Stop Watcher</button>
    <ol>
      <li v-for="x in results">{{ x }}</li>
    </ol>
  </div>
</template>

<script>
export default {
  data() {
    return {
      value: 4,
      results: [],
      stopFunc: null
    };
  },
  mounted() {
    this.stopFunc = this.$watch('value', function() {
      this.results.push('$watch() method')
    })
  }
};
</script>

<style scoped>
div {
  border: solid black 1px;
  padding: 10px;
}
</style>
執行示例 »

示例 5

使用點分隔路徑字串,以便 $watch() 方法可以監聽 'value' 物件中的 'country' 屬性。

<template>
  <h2>Example $watch() Method</h2>
  <p>The watcher is set up to watch 'value.country' and will therefore detect when the country is changed inside the 'value' object.</p>
  <div>
    <p>Register a new country for Stuart to live in:</p>
    <p><input type="text" v-model="inpVal"></p>
    <button v-on:click="regHobby">Register</button>
    <ol>
      <li v-for="x in watchMessages">{{ x }}</li>
    </ol>
  </div>
  <p>Current 'value' object:</p>
  <pre>{{ this.value }}</pre>
</template>

<script>
export default {
  data() {
    return {
      inpVal: null,
      value: {
        owner: 'Stuart',
        address: 'Faraway Lane',
        country: 'Mexico'
      },
      watchMessages: []
    };
  },
  methods: {
    regHobby() {
      this.value.country = this.inpVal;
      this.inpVal = null;
    }
  },
  mounted() {
    this.$watch('value.country', function () {
      this.watchMessages.push('watcher triggered')
    });
  }
};
</script>

<style scoped>
div {
  border: solid black 1px;
  padding: 10px;
}
</style>
執行示例 »

示例 6

$watch() 方法中使用函式來監聽多個值的變化。

<template>
  <h2>Example $watch() Method</h2>
  <p>Using a function as the first argument in the watcher to watch for changes in the sum of value A and value B.</p>
  <div>
    <p>Register a new country for Stuart to live in:</p>
    <p>Value A: <input type="range" min="-10" max="20" v-model="inpValA"> {{ inpValA }}</p>
    <p>Value B: <input type="range" min="-10" max="20" v-model="inpValB"> {{ inpValB }}</p>
    <ol>
      <li v-for="x in watchMessages">{{ x }}</li>
    </ol>
  </div>
</template>

<script>
export default {
  data() {
    return {
      inpValA: 2,
      inpValB: 4,
      watchMessages: []
    };
  },
  mounted() {
    this.$watch( 
      ()=> Number(this.inpValA) + Number(this.inpValB), 
      function (newVal,oldVal) {
        this.watchMessages.push('watcher triggered. A + B = ' + newVal)
      }
    );
  }
};
</script>

<style scoped>
div {
  border: solid black 1px;
  padding: 10px;
}
li {
  background-color: lightgreen;
}
</style>
執行示例 »

相關頁面

Vue 教程:Vue 監聽器

Vue 教程: Vue 方法

Vue 教程: Vue v-on 指令

Vue 教程:Vue Template Refs

Vue 參考:Vue $refs 物件

JavaScript 教程:JS 箭頭函式


×

聯絡銷售

如果您想將 W3Schools 服務用於教育機構、團隊或企業,請傳送電子郵件給我們
sales@w3schools.com

報告錯誤

如果您想報告錯誤,或想提出建議,請傳送電子郵件給我們
help@w3schools.com

W3Schools 經過最佳化,旨在方便學習和培訓。示例可能經過簡化,以提高閱讀和學習體驗。教程、參考資料和示例會不斷審查,以避免錯誤,但我們無法保證所有內容的完全正確性。使用 W3Schools 即表示您已閱讀並接受我們的使用條款Cookie 和隱私政策

版權所有 1999-2024 Refsnes Data。保留所有權利。W3Schools 由 W3.CSS 提供支援