Home > Mobile >  Watch in vue 3 setup
Watch in vue 3 setup

Time:06-18

I've to change my current vue code to vue3 <script setup> code but I've problem with 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 it should look like in <script setup>?

CodePudding user response:

vuejs 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

CodePudding user response:

Try it like this.

import { defineComponent } from "vue";

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