Unable to locate Vue.js $ref reference

I am attempting to dynamically adjust the padding of an element through inline styles, depending on the height of its parent. My approach involves:

<div class="stock-rating positive" ref="stockRating">
    <div class="stock-rating-start-end" v-bind:style="{ paddingTop: paddingTop }">
        <div>{{ rating.value_start }}</div>
        <div>to</div>
        <div>{{ rating.value_end }}</div>
    </div>
</div>

The value for paddingTop will be computed property. However, I encountered a problem where I couldn't access the $ref of the parent element (stockRating) in the computed property function, even though it appeared to be present within the $refs object.

paddingTop : function(){
    console.log(this.$refs);
    console.log(this.$refs.stockRating);
    /*computation here*/
}

Upon using console.log, the output revealed:

https://i.sstatic.net/oEn6R.png

If this.$refs includes the stockRating property but this.$refs.stockRating is undefined, how do I resolve this discrepancy and successfully compute the desired padding based on the parent element's height?

Answer №1

To ensure that the DOM is ready and the component has been mounted in Vue, you need to notify it.

new Vue({
  el: "#app",
  computed: {
    itemRef() {
      console.log(this.$refs.item)
      return this.ready ? this.$refs.item : false
    }
  },
  data: () => {
    return {
      ready: false
    };
  },
  mounted() {
    this.ready = true;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id='app'>
  <div ref="item" class="item">
    {{itemRef}}
  </div>
</div>

Answer №2

Even though your $refs.stockRating is defined and available, it won't actually be accessible until the component is mounted, as discussed here.
I haven't tested it myself, but I believe that if you were to console.log your $refs.stockRating within the mounted(){} component method, it should not be empty.

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

The task of mapping an array of objects with nested values using JavaScript is proving to

Attempting to convert an array of objects with nested values in child objects like: const objs = [{ "B": { "value": 1, }, "D": { "value": "45" }, "E": { "value": "234" }, ...

Is the reordering of items in an Angular JS array causing a malfunction with the first item

It appears that there may be a syntax error present in my code. Within my controller, I have a set of 4 functions: adding a new item, deleting the current item, moving an item backward (up) in the array, and moving an item forward (down) in the array. Al ...

How can I use Grid List and Icon Button in Material UI as individual buttons with onClick functionality?

I've been experimenting with the grid list feature from the Material UI framework, found here: https://material-ui.com/components/grid-list/#grid-list-with-titlebars My current challenge involves adding onClick actions to both the GridListTile compon ...

The active tabs or placeholders do not update properly when I click on them

Is there anyone who can help figure out why the tabs are not functioning as expected? The goal is for the tabs to change the input field placeholder and perform a search based on the active tab. If you're able to assist, please review my complete cod ...

Tips for resolving state change issues in VUEX

I am facing an issue with making changes to the state while splicing an element from another array without affecting the state itself. To clarify, I want to remove one element from the array arrayWithFilters = [] without altering the state.selected.filte ...

What is the process of synchronizing state in react.js?

I am struggling to update the state and component in my code. When I press a button and change the value of one of the props in the popup component, the prop value does not get updated. I suspect this issue is due to using setState. I researched a possible ...

Using Vue with Express (specifically NestJS) may seem like a daunting challenge, especially if you are working with the runtime-only build

I am facing difficulties in integrating Vue as a view system with a framework called Nest using Express. I underestimated the complexity of adapting Vue. I am seeking guidance to ensure I am on the right track and avoid using Vue directly. Firstly, the e ...

Calculating the total of fields from populated documents using Mongoose

In my application, I have two main models: User and Track. A User can complete various Tracks and earn points for each one. The schema for the User model looks like this: let userSchema = new mongoose.Schema({ name: {type: String, required: true}, ...

Is it possible to incorporate a React app as a component within a static HTML page?

Looking to integrate the react-csv-viewer component into a static HTML page without deploying it on a local server. I've tried following the instructions from the React tutorial, but am struggling with the build process. My goal is simple - to use th ...

Vue - Struggling to invoke sweetalert2 within a method

I'm encountering an issue with launching sweetalert within a Vue method. When I directly call the sweetalert in the script, it works fine. However, when I try to launch the sweetalert upon clicking a button, nothing happens (no errors in the console). ...

Issue encountered with JavaScript AJAX involving a Cross Domain ASMX Web Service JSONP Request

I have been working on a local web service that I believe fits the criteria for making cross-domain JavaScript calls to access external data within Dynamics CRM. However, I am facing some challenges in creating the JavaScript AJAX code needed to connect wi ...

Is it feasible to directly load image objects into jQuery colorbox?

Currently, I am working with the "colorbox" jQuery plugin and I have a specific requirement to dynamically load a set of preloaded image objects into colorbox. The challenge lies in the fact that I have three different image sizes - thumbnail, display, an ...

Failure when running npm start command in Nest js

After setting up a fresh Nest js on a new EC2 machine, I encountered an error when trying to run it for the first time. The error message indicated that the npm install process failed abruptly without any visible error: ubuntu@ip-172-31-15-190:~/projects/m ...

Initiate an animation in Wordpress once the entire page has finished loading

Recently, I incorporated some "raw html" elements with animations into my WordPress site. However, the issue I'm facing is that these animations kick off as soon as the page loads, without waiting for the preloader to complete and display the actual c ...

Maintaining Existing Filters and Incorporating Additional Filters in React/Next.js Data Filtering

I'm currently facing a challenge with filtering data in React/Next.js. The issue I'm encountering is that whenever I set a new filter, the previous filters get removed. For instance, if a user performs a search, it works fine but the tag filters ...

Getting the value of a repeater label in JavaScript can be achieved by following these

Here is my javascript code: function btnEditClick() { alert(document.getElementById('<%=LblRefPhyID.ClientID %>').value); } <asp:Repeater ID="repeaterRefPhysicianList" runat="server"> <ItemTemplate> < ...

Is there a way to modify the variable in order to switch the font of the heading every second using CSS and JavaScript?

I'm trying to create a heading that changes fonts every second, but I'm having trouble changing the variable to set it to another font. Check out my code here. Despite watching tutorials, everything seemed too confusing. var root = document.q ...

Creating one div to initiate the contents to fadeToggle and another div to cease the fadeToggle animation utilizing the setInterval function in JavaScript

Here is the link to my Fiddle: http://jsfiddle.net/tmanundercover/62ap2/ CSS #targetedDiv, #otherDiv { border: 1px solid; } HTML <div id="targetedDiv">&nbsp<span id="fakeCursor">|</span></div> <br> <div id="othe ...

Leverage the power of forkJoin in JavaScript by utilizing objects or sourcesObject

I'm currently facing an issue with my code snippet below: getInformations().subscribe( informations => { let subs = []; for (const information of informations) { subs.push(getOtherDetails(information.id)); } ...

Encountered a $resource configuration issue while making a request to the SharePoint REST service with Angular

In an old sample app without angularJS, a rest service is called in the following way: This app does not use angularJS. var listName = "Events"; // the url to use for the REST call. var url = SPAppWebUrl + "/_api/SP.AppContextSite(@target ...