Vue中的watch用法
Vue.js中的watch主要用于觀察Vue實例上的數(shù)據(jù)變動。
栗子:
<template>
? ? // 觀察數(shù)據(jù)為字符串或數(shù)組
? ? <input v-model="example0" />
? ? <input v-model="example1" />
? ? // 單觀察數(shù)據(jù)example2為對象時,如果鍵值發(fā)生變化,為了監(jiān)聽到數(shù)據(jù)變化,需要添加deep:true參數(shù)
? ? <input v-model="example2.inner" />
</template>
<script>
? ? export default {
? ? ? ? data () {
? ? ? ? ? ? return {
? ? ? ? ? ? ? ? example0: "",
? ? ? ? ? ? ? ? example1: "",
? ? ? ? ? ? ? ? example2: {
? ? ? ? ? ? ? ? ? ? inner: 1
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? },
? ? ? ? watch: {
? ? ? ? ? ? example0 (curVal, oldVal) {
? ? ? ? ? ? ? ? console.log(curVal, oldVal)
? ? ? ? ? ? ?},
? ? ? ? ? ? example1: 'a',? // 值可以為methods的方法名
? ? ????????example2: {
????????????????//?注意:當(dāng)觀察的數(shù)據(jù)為對象或數(shù)組時,curVal和oldVal是相等的,因為這兩個形參指向的是同一個數(shù)據(jù)對象
????????????????????handler (curVal, oldVal) {
????????????????????????console.log(curVal, oldVal)
????????????????????},
????????????????????deep: true
????????????????}
? ? ? ? },
????????methods: {
????????????????a: function (curVal, oldVal) {
????????????????????????console.log(curVal, oldVal)
????????????????}
????????}
? ? }
</script>