Home > Web Front-end > JS Tutorial > body text

Problems with watch not detecting changes in object properties in Vue

亚连
Release: 2018-06-06 17:41:24
Original
2685 people have browsed it

This article mainly introduces the solution to the problem that watch in Vue cannot detect changes in object attributes. Now I share it with you and give you a reference.

Preface

A problem was discovered during the development of vue: changing the properties of the object in vue.$data, watch cannot observe the change, but in fact the object Properties are subject to change. This... is a bit unbelievable!

Text

<template>
 <p>
  <dl>name: {{option.name}}</dl>
  <dl>age: {{option.age}}</dl>
  <dl>
   <button @click="updateAgeTo25">update age with 25</button>
  </dl>
 </p>
</template>

<script>
export default {
 data () {
  return {
   option: {
    name: "isaac",
    age: 24
   }
  }
 },
 watch: {
  option(val) {
   console.log(val)
  }
 },
 methods: {
  updateAgeTo25() {
   this.option.age = 25
  }
 }
}
</script>
Copy after login

##As shown in the results, option.age has been updated, but The option function in watch is not triggered.

Is vue’s watch hook so useless? I don't believe it anymore.

Deep watch

 ...
 watch: {
  option: {
   handler(newVal) {
    console.log(newVal);
   },
   deep: true,
   immediate: true
  }
 },
 ...
Copy after login
If you need deep watch, you need to enable the deep attribute

##As shown in the results.

In addition, you will find that the option is printed before the age changes. This is because the immediate attribute is turned on and set to true.

The callback will be after the listening starts. Called immediately

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

How to solve the problem when Vue.js displays data, the page flashes

How to use vue-router to set each The title method of the page

How to implement page jump in vue and return to the initial position of the original page

The above is the detailed content of Problems with watch not detecting changes in object properties in Vue. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template