Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access ref element that being conditionally rendered in v-if - Vue

I have an element that being conditionally rendered with v-if="isLogged", if a user is logged in:

<div
  v-if="isLogged"
  class="chatBlock"
  ref="chat"
></div>

I'm trying to get scroll height of the chat reference in a mounted () function - this.$refs.logged.scrollHeight, but it's not possible, because if a user is not logged in, then this div won't be rendered on a mounting stage, so even if a user logs in - it won't work, because mounted stage already passed.

Is it possible to track element appearance in a DOM using watch method?

UPDATE

Added watcher, as Steven suggested below in a mounted ():

this.$store.watch(
  (state) => {
    return this.$store.getters.isLogged
  },
  (newValue, oldValue) => {
    if (newValue) {
      this.chatHeight = this.$refs.chat.scrollHeight
    }
  }
)
like image 742
Alexander Kim Avatar asked Dec 02 '18 07:12

Alexander Kim


1 Answers

The accepted answer did not work for me. The watch does not guarantee that the element has already been rendered.

To make sure that the element is available, I had to use $nextTick

 if (newValue) {   
     this.$nextTick(function () {
         this.chatHeight = this.$refs.chat.scrollHeight
    })
}

This will cause the code to be executed after the next DOM update cycle.

like image 116
Thomas Kainrad Avatar answered Nov 15 '22 04:11

Thomas Kainrad