简体   繁体   中英

Not calling watch even after the prop change in vue.js

I can't use immediate:true , except immediate true is another thing I can do? Why watch is not calling even after the data change in prop? Only it is calling for the first time when application loads.

export default {
  name: "Tabs",
  data () {
    return {
      init: false,
      currentTab: "tab-0",
      tab: null,
    }
  },
  props: {
    config: {
      type: Object,
      default: undefined
    },
    dynamicSelection: 0
  },
}

watch: {
    config: {
      handler: function (val) { //need to do something }
          }
       }

I suspect you are experiencing the 'reactivity caveat' of vue. It probably depends on how you are mutating the object that you are passing as a config value.

For example:

<template>
  <div id="app">
    <HelloWorld :config="config"/>
    <button @click="clicked1">This will update</button>
    <button @click="clicked2">This will not update</button>
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld";

export default {
  name: "App",
  components: {
    HelloWorld
  },
  data(){
    return {
      config: { x: 1 }
    }
  },
  methods: {
    clicked1(){
      this.config = { x: this.config.x + 1 }
    },
    clicked2(){
      this.config.x++
    }
  }
};
</script>

If HelloWorld is watching the config value, it will only update when the entire object is reset.

Try adding a deep: true to your watcher.

  watch: {
    config: {
      handler(){
        this.watchCounter++
      },
      deep: true
    }
  }

I added a codesandbox link with some sample code: https://codesandbox.io/s/charming-cohen-jgn3d Click on the buttons and notice that it will not update when "This will not update" is clicked. Uncomment the deep: true inside the HellowWorld component to see how it fixes the issue.

Read more about the reactivity caveats on the official docs. https://v2.vuejs.org/v2/guide/reactivity.html#For-Objects

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM