W
W
wakenby2021-04-12 15:58:55
Vue.js
wakenby, 2021-04-12 15:58:55

How to get the value of a variable in watch in vue?

I created a notification component, which receives an array of messages, they are displayed, and after N - time they are deleted, here is the code:

export default {
  props: {
    notifications: {
      type: Array
    }
  },
  methods: {
    removeNotification () {
      setTimeout(() => {
        this.notifications.pop()
      }, 3000)
    }
  },
  computed: {
    notificationsLength () {
      return this.notifications.length
    }
  },
  watch: {
    notificationsLength (newValue, oldValue) {
      if (newValue > oldValue) this.removeNotification()
    }
  }
}


The bottom line is that when a new notification is added, setTimeout is launched and the last notification is deleted after N - time. But watch fires not only when added from outside the notification, but also when removed. I had to look for a way out, and write a computed property to get information about whether a notification was added.

And the essence of the question, is it possible to do without a computed property to get the length of the resulting array in watch?

Tried like this but doesn't work:

export default {
  props: {
    notifications: {
      type: Array
    }
  },
  methods: {
    removeNotification () {
      setTimeout(() => {
        this.notifications.pop()
      }, 3000)
    }
  },
  watch: {
    notifications (newValue, oldValue) {
      if (newValue.length > oldValue.length) this.removeNotification()
    }
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-04-12
@wakenby

the essence of the question, is it possible to do without the computed property, to get the length of the resulting array in watch?

Can. Length and track:
watch: {
  'notifications.length'(newValue, oldValue) {
    ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question