axecopfire
axecopfire

Reputation: 652

Vue call a function within watch after updated

Trying to change scrollTop of an element only after messages has updated and rendered. Is there a Vue specific way to do this?

<template lang="pug>
section
  ul#messages(refs="messages")
    Message
  Form(@submit.prevent="send")
</template>

<script>
import Message from './message';
import Form from './form';
export default {
  components: {
    Message,
    Form
  },
  data () {
    return { messages: [] }
  },

  watch: {
    messages: function () {
      // Call a function after `updated` that sets:
      // this.$refs["messages"].scrollTop = this.$refs["messages"].scrollHeight;
    }
  },
  methods: {
    send: function (data) {
      this.messages.push(data);
    }
  }
}

</script>

Upvotes: 1

Views: 867

Answers (1)

axecopfire
axecopfire

Reputation: 652

Put a conditional inside the updated lifecycle hook that checks for a boolean of whether you have scrolled or not. Update that boolean in the message watcher.

<template lang="pug>
section
  ul#messages(refs="messages")
    Message
  Form(@submit.prevent="send")
</template>

<script>
import Message from './message';
import Form from './form';
export default {
  components: {
    Message,
    Form
  },
  data () {
    return { messages: [], scrolled: false }
  },
  updated: function() {
    if(!this.scrolled) {
      // Set scroll height
      this.scrolled = true;
    }
  },
  watch: {
    messages: function(arr) {
      this.scrolled = false;
    },
  },
  methods: {
    send: function (data) {
      this.messages.push(data);
    }
  }
}

</script>

Upvotes: 2

Related Questions