watch监听组件中的任何东西

监听data数据的变化

watch:{
    data(oldVal, newVal) {
        console.log(oldVal, newVal)
    }
}

监听list数据的变化 深度监听

data() {
    return {
        list: {
            'id': 1,
            'type': 0
        },
        number: 0
    }
},
watch:{
    list: {
        handler(newVal) {
            console.log(newVal)
        },
        deep: true
    }
}

监听计算属性

computed: {
    computedProperty () {
      return this.id ? '是' : '否'
    }
  }
watch: {
    computedProperty (newVal) {
      console.log(1)
    }
  }

监听props传入的值

props: {
    flag: {
      type: Boolean,
      default: false
    }
},
watch: {
    flag (newVal) {
      console.log(1)
    }
}

监听对象属性 深度监听

watch: {
	'user.name': {
		handler(newVal, oldVal){
			console.log(newVal)
		}
		deep: true
	}
}

监听路由参数的变化

vue-router导航切换时,如果两个路由渲染同一个组件,组件会重用,组件的生命周期钩子(created)不会在被调用,使组件的部分数据无法根据path的改变而更新

因此我们可以在watch中监听路由的变化,当路由改变时,重新调用created中的内容

watch: {
    $route (newVal) {
      this.List()
    }
  }

猜你喜欢

转载自blog.csdn.net/Qiemo_/article/details/125323068