Vue中的watch用法
Vue.js中的watch主要用于觀察Vue實(shí)例上的數(shù)據(jù)變動(dòng)。
栗子:
<template>
? ? // 觀察數(shù)據(jù)為字符串或數(shù)組
? ? <input v-model="example0" />
? ? <input v-model="example1" />
? ? // 單觀察數(shù)據(jù)example2為對(duì)象時(shí),如果鍵值發(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ù)為對(duì)象或數(shù)組時(shí),curVal和oldVal是相等的,因?yàn)檫@兩個(gè)形參指向的是同一個(gè)數(shù)據(jù)對(duì)象
????????????????????handler (curVal, oldVal) {
????????????????????????console.log(curVal, oldVal)
????????????????????},
????????????????????deep: true
????????????????}
? ? ? ? },
????????methods: {
????????????????a: function (curVal, oldVal) {
????????????????????????console.log(curVal, oldVal)
????????????????}
????????}
? ? }
</script>