What is the best way to retrieve the dynamic width of a specific div element within a Vue.js

I am currently facing an issue while trying to obtain the width of a container dynamically in Vue using refs. The problem I am encountering is that it either shows the previous value or returns undefined. I suspect there might be a mistake in my approach. My main goal is to retrieve the width of a specific div in real-time.

In my quest for a solution, I came across helpful discussions on Vue - Setting the width of a component dynamically, vuetify.js how to get full width of v-container, and Vue - setting width of an element equal to the width of another element, but unfortunately, none of them worked for me.

const app = new Vue({
   el: '#app',
   mounted () {
    this.screenWidth()
   },
   methods: {
     screenWidth() {
      console.log("screen", this.$refs.container?.offsetWidth);
      return `${this.$refs?.container?.offsetWidth}`;
    },
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app" ref="container">
   Screen {{ screenWidth() }}
</div>

Answer №1

In addition to the solution provided in Vue JS - How to get window size whenever it changes, you can ensure you always have the width by including a mounted() method.

const app = new Vue({
   el: '#app',
   data() {
    return {
      sWidth: null
    };
  },
  created() {
    window.addEventListener("resize", this.screenWidth);
  },
  mounted () {
    this.screenWidth()
  },
  destroyed() {
    window.removeEventListener("resize", this.screenWidth);
  },
  methods: {
    screenWidth() {
      this.sWidth = this.$refs.container?.offsetWidth;
    },
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app" ref="container">
    screen {{ sWidth }}
</div>

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

Ways to retrieve the ID of the clicked element from the child up to the parent

I currently have a Parent component and a Child component. The Child component contains inner elements called notes, with "delete" being one of them. My goal is to have the Child component return an ID to the Parent component when the delete element is cl ...

Creating an X pattern on an HTML5 canvas and detecting intersections with a perimeter

I am currently developing a maze game using HTML 5. Below is the function I have implemented to draw an "X" on the canvas (the player will guide the X through the maze using touchpad). dim = 8; function rect(x,y,xdim){ ctx.beginPath(); ctx.moveT ...

Expression enclosed in double quotes within a JavaScript string

Our company has encountered an issue with an FTL that involves a link with JavaScript functionality. The problem arises when the value contains an apostrophe, causing the link to break. To address this, we utilized the js_string method to solve the issue. ...

Scrolling and looping through an array using jQuery or JavaScript

Using Lettering.js, I have successfully generated a set of <span> elements with the class "char*", where * represents an integer. The array of these elements is created in the following manner: var characterArray = $("[class^='char']"); B ...

retrieve information in json format from a specified web address

I need to figure out why the data from a specific URL is not being displayed properly on my node application. It seems like there might be an error in my code. const extractRefDefaultSchema = async (data) => { const url = "https://mos.esante.gouv.f ...

Changing the border of an iframe element using jQuery or Javascript from within the iframe itself

Is it possible to set the border of an iframe to zero from within the iframe itself using JavaScript or jQuery? Any guidance on how this can be achieved would be greatly appreciated. Thank you! ...

Is there a way for me to view the output of my TypeScript code in an HTML document?

This is my HTML *all the code has been modified <div class="testCenter"> <h1>{{changed()}}</h1> </div> This is my .ts code I am unsure about the functionality of the changed() function import { Component, OnInit } f ...

Can custom HTML elements be designed to function similarly to standard ones?

What is the best way to create a custom HTML element that functions as a link without relying on inline Javascript? For instance: <x-button href="...">...</x-button> Can I develop an element like <x-button> that can accept an attribute ...

Why is it that I am unable to utilize the post data stored in $var within my PHP document when making an Ajax call?

Hey there! I've got this function that makes an ajax call. But, for some reason, the $value I'm passing isn't defined in my showuser.php file. Can you help me figure out why? function showUser2(value) { var xhr = new XMLHttp ...

Can you explain the significance of the colon in this context?

Upon reviewing some SearchKit code snippets (composed with react/jsx and es2015), I came across the following line in a jsx file: const source:any = _.extend({}, result._source, result.highlight) I am curious about the purpose or significance of the colo ...

React component not rendering iteration over Set in JSX

I need help figuring out how to iterate through a JavaScript Set() that is being passed down in props within a React component. I am struggling to get anything to display on the screen when attempting to loop through it: {selectedCity.forEach((key, v ...

Using Javascript to Divide Table into Separate Tables each Containing a Single Row

Is there a way to divide the content of this table into three separate tables using JavaScript? It is important that each table retains its header information. Unfortunately, I am unable to modify the id's or classes as they are automatically generat ...

Give Jquery a quick breather

My goal is to have my program pause for 3 seconds before continuing with the rest of the code. I've been researching online, but all I can find are methods that delay specific lines of code, which is not what I need. What I would like to achieve look ...

Automatically populating and submitting a form after receiving search results via ajax

I have been struggling with this issue for a few days now and could really use some help from the experts here. I am new to sql, javascript, jquery, ajax, css, and php. Although I studied Computer Science in college 15 years ago, I seem to be missing some ...

Are you familiar with Vue.JS's unique router options: the 'history' and 'abstract' routers?

Currently, I am developing a VueJS application that involves a 5-step form completion process. The steps are linked to /step-1 through /step-5 in the Vue Router. However, my goal is for the site to return to the main index page (/) upon refresh. One solu ...

Encountered an issue retrieving tweets from the Twitter API 1.1

I recently completed an online tutorial from this site: However, I'm encountering an error message that simply says 'error: ' without any additional information. To start, here is my PHP script used to fetch the JSON output: <?php sess ...

Having difficulty passing data manually to createRangeChart in Ag-Grid

Initially, I am passing unprocessed raw data to ag-Grid to populate the grid, resulting in a chart with randomly arranged ages. I now need to sort and process the age data before passing it to my range chart in order to create a sorted chart, while keeping ...

Unable to retrieve the value from the selected radio button

Below is the provided HTML: <form> <div class="form-group"> <div class="checkbox-detailed male_input"> <input type="radio" name="gender" id="male" value="male"> <label for="male"> ...

Retrieve the output from PHP in JSON format and then utilize jQuery to parse it

I am currently working on a jQuery function $.post(file.php), where the data is being sent to "file.php" and returned in JSON format using json_encode(). Although I am able to successfully retrieve the result, I am unsure how to separate the individual i ...

Refreshing the page when the hide/show button is clicked with jQuery

I have a situation where I am using jQuery to toggle the visibility of a div by clicking on show/hide buttons. However, I am facing an issue where the code does not work as intended. Every time I click the buttons, the div reverts back to its original stat ...