Ways to access a conditional rendered ref element in Vue using v-if

I have a specific element that is conditionally rendered using v-if="isLogged" when a user is logged in:

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

The issue I'm facing is trying to retrieve the scroll height of the chat reference within the mounted() function - specifically using this.$refs.logged.scrollHeight. However, this proves to be challenging because if a user is not logged in, the div will not be rendered during the mounting stage. Consequently, even if a user logs in afterward, it won't work as the mounted stage has already passed.

Is there a way to monitor the appearance of an element in the DOM by utilizing the watch method?

UPDATE

In response to Steven's suggestion below, I have incorporated a watcher in the mounted():

this.$store.watch(
  (state) => {
    return this.$store.getters.isLogged
  },
  (newValue, oldValue) => {
    if (newValue) {
      this.chatHeight = this.$refs.chat.scrollHeight
    }
  }
)

Answer №1

The solution provided did not work in my case as the watch function does not ensure that the element is already rendered on the DOM.

In order to ensure that the element is available, I had to implement the use of $nextTick

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

This will ensure that the code is executed after the next DOM update cycle.

Answer №2

To implement a watch feature for isLogged, you need to add logic to retrieve your chat reference when it is active. It's important to include a check on whether your component is mounted and organize your logic in a centralized function.

Here's how you can set up your component:

const componentOptions = {
  methods: {
    checkChat() {
      const chatRef = this.$refs.chat
      if (chatRef) {
        // Add your code here...
      }
    }
  },
  mounted() {
    this.checkChat();
  },
  watch: {
    isLogged(value) {
      if (value) {
        this.checkChat();
      }
    }
  }
}

—-

Alternatively, you can utilize v-show instead of v-if to render the element while keeping it hidden when necessary.

Answer №3

After following Steven's advice, I decided to switch to v-show, which ended up being the perfect solution for my situation. Using v-show proved to be a more efficient choice compared to v-if because of its cost-effective toggling capabilities. If you're curious about the differences, check out this insightful answer:

Answer №4

Consider implementing a nextTick around the call to the ref. By doing this, the ref will be available when the code is executed within the block.

Check out this demonstration:

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.4.8/vue.global.min.js"></script>

<div id="app">
  <div>
    <button @click="handleToggle" style="margin-right:0.5rem;">Toggle</button>
    <my-element v-if="visible" ref="myElement" />
  </div>
</div>

<script>
  const {
    createApp
  } = Vue

  createApp({
    components: {
      myElement: {
        template: "<span>{{ text }}</span>",
        data() {
          return {
            text: '',
          };
        },
      }
    },
    data() {
      return {
        visible: false,
      }
    },
    methods: {
      handleToggle() {
        this.visible = !this.visible;

        if (this.visible) {
          this.$nextTick(() => {
            this.$refs.myElement.text = "I'm visible";
          });
        }
      },
    }
  }).mount('#app')
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

After modifying the code for a 3D map exported from qgis2threejs, the page now sits empty, waiting

I'm looking to make modifications to the code within a 3D map that was created using qgis2threejs, which is QGIS's plugin for creating 3D webmaps. Although I don't have much experience with the threejs library or JavaScript, I want to alter ...

ngAnimateSwap - animations do not function as intended when boolean expressions are utilized

I adapted the original ngAnimateSwap demonstration from the AngularJS documentation to utilize a boolean expression for triggering the slide animation. Initially, I anticipated the banner to switch back and forth between 'true' and 'false&a ...

Ways to determine if the v-menu is currently visible or hidden

I am currently working on a button with a logo displayed. The hover functionality is working fine, but I want the icon to change to a hamburger when the menu is opened and stay that way. Is there an option in v-menu that checks if the menu is open or shoul ...

Encountering a syntax error while utilizing jQuery AJAX

Recently, I've started learning jQuery and came across an AJAX example that intrigued me. The task at hand is to pass a PHP variable to another PHP page without refreshing the entire webpage. After some tinkering, I managed to come up with the code sn ...

JavaScript code to locate the most pertinent strings within an array based on a specific substring

I'm working with a large array containing names of people, such as: let names = [ "John Brown", "Tristan Black", "Carl Jobbs", "Aidan Burrows", "Taylor Joe" ]; When given an input, I want to return the top 5 most relevant results ...

The proper method for utilizing the clipped prop on the <v-navigation-bar/> component within Vuetify is as follows

Looking for the correct way to apply the clipped prop to <v-navigation-draw/> in a Vuetify application in order to ensure that the navigation drawer sits below the app-bar. Here is what I have tried so far. Started with a new project: $ vue create ...

My website has a navbar button that is not directing to the intended section of the screen

I have created this HTML code for my Navbar buttons: <button class="navbar-toggle" data-toggle = "collapse" data-target=".navHeaderCollapse"> <span class="icon-bar"></span> <span class="icon-bar">< ...

Generating examples of two models that are interdependent

In my Javascript form, I have implemented an AJAX POST request that successfully creates a new instance of a model called Component. Now, my goal is to allow users to input keywords for the Component model through the same form. To achieve this, I have al ...

At what point can we rely on the accuracy and timeliness of Element.getBoundingClientRect?

I am currently in the process of developing some code that utilizes Element.getBoundingClientRect (gBCR), combined with inline style updates, to carry out calculations. This particular project is not intended for a general website, so I am not interested i ...

Discord.js version 13 encountered an issue where it is unable to access properties of undefined while

Having trouble with creating a warn system that just won't work! I've tried various solutions but nothing seems to be fixing it. Would greatly appreciate any help! Error Log: [FATAL] Possibly Unhandled Rejection at: Promise Promise { <reje ...

Ways to create a self-contained video viewer

Is it possible to create a self-contained video player similar to jwplayer or the YouTube video player using just HTML, CSS, and JavaScript? I know that I can build a video player by utilizing the video tag along with some custom javascript and css, but ho ...

Error Encountered: "JSON Post Failure in ASP.net MVC resulting in 500

Whenever I attempt to send a variable to JSON on ASP.net MVC, I encounter the following error: jquery-2.2.3.min.js:4 GET http://localhost:58525/Order/GetAddress/?userid=42&email=asandtsale%40gmail.com 500 (Internal Server Error) This is my controller ...

php utilizing javascript to generate encrypted data for a hidden file

Within my MVC application, I have implemented Raty for rating images. Below is the code snippet: <div class="container"> <form method="post" class='form' role='form' action="?section=photo&view=addVote"> <input t ...

When transitioning between single-page Angular applications using Protractor, a "JavaScript error: document unloaded while waiting for result" may be encountered

I came across this article discussing the issue of a Javascript error related to a document being unloaded while waiting for a result: JavascriptError: javascript error: document unloaded while waiting for result Although the solution provided seems to wo ...

Error: JSX elements that are next to each other must be contained within a parent tag

I am trying to display articles on a page using ReactJS, but I encountered an issue where I need to wrap enclosing tags. It seems like React doesn't accept identical tags next to each other. How can I effectively show tabular data? render() { r ...

Avoid the mounting of a Vue component using v-if while still maintaining the transition animation

Here is my code snippet demonstrating how I created a modal using Vue. The issue I am encountering revolves around maintaining the transition effects while conditionally mounting the Vue component. Upon clicking the button in the initial code block, the mo ...

What is the process for implementing document.ondrop with Firefox?

I'm experiencing an issue where the document.ondrop function seems to be working in Chrome, but not in Firefox. Here's a link to an example demonstrating the problem: In the example, if you try to drop a file onto the page, it should trigger an ...

Having trouble accessing the information stored in the Firebase Database?

As a newcomer to Firebase and JS, I am attempting to showcase user information on a webpage that is stored within the Firebase database. The data format resembles the image linked here I have written this Javascript code based on various tutorials. Howev ...

Stop the webpage from scrolling when clicking on a ui-grid field

Is there a way to prevent page scrolling when clicking on a row field in ui-grid? I'm working with a page that has ui-grid, and each row includes an anchor tag with a URL value linked and target="_blank" to open in a new tab like the example below: ...

A cube created in Three.js featuring a unique texture on each of its six faces

I'm attempting to generate a cube using three.js with unique textures on each face, resembling a dice. This is being developed in a sandbox environment where a rotating cube with dice images (1-6) on each side will be created. Once completed, I plan t ...