vue.jsvuejs3watch

Watch in Vue.js 3 setup


I've to change my current Vue.js code to Vue.js 3 <script setup> code, but I've problem with the watch property. What is proper syntax for watch in <script setup>?

Current code:

  watch: {
    config: {
      handler(newConfig) {
        if (this.$refs && this.$refs.range && this.$refs.range.noUiSlider) {
          this.$refs.range.noUiSlider.destroy()
          const newSlider = this.noUiSliderInit(newConfig)
          return newSlider
        }
      },
      deep: true,
    },
  }

How should it look like in <script setup>?


Solution

  • Vue.js is known for its excellent documentation - Watchers (make sure you select composition API).

    Basically:

    import {watch} from "vue";
    //
    //
    //
    watch(config, (newConfig) => {
        // Your code
    }, { deep: true });
    

    Obviously, "Your code" will be different to what you currently have, but I assume you only needed help with how to use watch.

    i.e., all the this.* is obviously different in composition API (where you never use this).

    It's worth noting that When you call watch() directly on a reactive object, it will implicitly create a deep watcher - the callback will be triggered on all nested mutations: Deep Watchers

    So, you may not even need the deep:true option - of course with such a small code fragment in the question, it's hard to say what config is.