Determine the width of the containing element using Vue.js

I have been working on implementing a Vue.js component called CamViewMatrix. My goal is to retrieve the width of CamViewMatrix's parent element within the component itself (specifically in the created() method of CamViewMatrix), in order to perform some calculations with it. This is necessary for creating responsive time-based charts, which require an initial width value to work properly.

<div>
  <div class='controller-wrapper'>
    ...
  </div>
  <CamViewMatrix v-bind:cameras='cams' />
</div>

I attempted to assign an id to the parent element and pass it as a prop to CamViewMatrix. I then tried to retrieve the parent element using getElementById, but unfortunately, it did not work. See the code snippet below:

<div id='parentid'>
  <div class='controller-wrapper'>
    ...
  </div>
  <CamViewMatrix v-bind:cameras='cams' parentId='parentid' />
</div>

And here's the relevant section inside the CamViewMatrix component:

<script>
export default {
  name: 'CamViewMatrix',
  props: {
    parentId: {
      type: String,
      required: true,
    },
    ...
  },
  created() {
    console.log(document.getElementById(this.parentId)); // 👈️ logs null
    ...
  }
}

Unfortunately, with the above code, I was unable to retrieve the parent element (it's logging null). I also tried using ref and $parent, but encountered the same issue. I would greatly appreciate any assistance you can provide with this problem.

Thank you in advance.

Answer №1

created() is not the appropriate lifecycle hook for that task.

Referencing the lifecycle diagram in the documentation: https://v2.vuejs.org/v2/guide/instance.html#Lifecycle-Diagram

At the point of created(), the element has not been rendered, only the instance has been created.

It is recommended to perform such tasks within the mounted hook.

Furthermore, you can access the parent of your component using this.$parent and the element using this.$parent.$el.

For more information, see: https://v2.vuejs.org/v2/api/#Instance-Properties


If you need to target a specific element within the parent, create a reference and access it like this:

this.$parent.$refs.refNameYouAdded

If it's a Vue component, you will need to access $el again as follows:

this.$parent.$refs.refNameYouAdded.$el

If it's just an HTML element, this step is not necessary.


While the aforementioned solutions typically suffice, there may be scenarios where the parent component manipulates the elements, leading to inaccuracies.

In such cases, you can still access the correct parent element by using:

this.$el.parentElement

Answer №2

To achieve the same result with the composition api, one can utilize the getCurrentInstance method (please note that this is considered non-public).

import { getCurrentInstance  } from "vue";
const instance = getCurrentInstance();
instance?.proxy?.$el.parentElement.clientWidth

Alternatively, you can opt for the UseElementSize component from the vue core component library. This allows you to encapsulate your component and provide it with the necessary width information.

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

Delete JavaScript data array

I've been working on a project involving data manipulation in a JSON file. Although I can successfully add new names to the file, I'm facing an issue when trying to delete them. Instead of deleting, the inputted name gets added to the file again ...

Can someone explain the purpose of this code snippet: `const { foo = "bar" } = "baz"`?

I came across this code not too long ago and had trouble finding the answer online, so I'm turning to you for help. The specific code snippet is from a webpack configuration file: const { NODE_ENV = 'production', } = process.env; Appreci ...

Adjust the Pivot Point of a GLTF Model in ThreeJS Manually

Hey there, I have a GLTF model that I successfully loaded into my ThreeJS scene by using the code snippet below: gltfLoader.load('assets/models/coin/scene.gltf', (gltf) => { const root = gltf.scene; gltf.scene.traverse(functio ...

angularjs controller cross-validation for forms

I am faced with a dilemma involving two controllers: btnController and formController. Specifically, I need to submit a Form from another controller action while ensuring that the function in the controller is only called when the Form Validation is Valid. ...

Can VueJS components be configured with multiple types for a prop and multiple default values?

When defining props in Vue components, it is common to set the expected type and default value like so: export default { name: "myComponent", props: { myProp: { type: String, default: 'any text' } ...

Error: Trying to access a property that is undefined (specifically referencing 'rendered') has resulted in an uncaught TypeError

As a newcomer to React, I'm attempting to create a headless WordPress application. However, when I fetch a post, I only receive the first value. After fetching the post, I save it in the state: componentDidMount() { this.setState({ lo ...

Carry out numerous commitments across a range of elements

I have a list of objectIds and I want to perform operations on different collections based on each Id. I prefer executing the operations sequentially. var removeOperation = function(objectified){ return Comps.findOne({reviews : objectified}).populate([ ...

Having trouble parsing JSON elements separately

I am currently working on generating data to be utilized in a chart.js plot by utilizing C# Controller and javascript. The Controller method I have returns a JSONResult to a javascript function. public JsonResult GetPlansPerDoc(){ //Code to retrieve d ...

I want to show error messages using jquery only when the username or password is entered incorrectly. How can this be achieved?

document.getElementById("buttonClick").addEventListener("click", mouseOverClick); function mouseOverClick(){ document.getElementById("buttonClick").style.color = "blue"; } $("#buttonClick").hover(function() { $(this).css('cursor',&apos ...

Unable to display tags with /xoxco/jQuery-Tags-Input

I'm experimenting with the tagsinput plugin in a textarea located within a div that is loaded using the jquery dialog plugin. The specific plugin I am using is /xoxco/jQuery-Tags-Input. After checking that the textarea element is ready, I noticed th ...

Include category to the smallest element

I am attempting to use JQuery to find the height of the tallest element and then add that height to other elements that are shorter. My goal is to assign the class, main-nav-special-padding, to these shorter elements using my current JQuery code. I tried t ...

The issue arising where the callback function fails to execute after making an AJAX POST request

Within my function, I have an AJAX call that I want to make reusable. When the AJAX call is successful, I need to callback a function. var ajaxPostCall = function(data , url ,callback){ // Return the $.ajax promise $.ajax({ data: data, dataType: ...

Press the toggle button to switch the image display

Currently learning HTML and attempting to design a dashboard. I want to display the status (ON, OFF, OPEN, or CLOSED) of a room or door using an icon. I have images for open/close doors and lightbulbs. Need assistance in adding an element to all the exist ...

VueJS: Unable to loop through an Object

Here is the code snippet that I am currently working with: console.log("My Object is:"); console.log(this.LoadedBaseMapLayersContent); for(obj of this.LoadedBaseMapLayersContent) { // console.log(obj); console.log("can't get this string"); } I am ...

Insert an HTML element prior to the content using the ng-bind directive

I am working with a table that is generated by an ng-repeat loop and connected to a model using ng-bind. In the first column, I want to dynamically add an HTML element based on a specific condition. How can I accomplish this? <!doctype html> <htm ...

Utilize jQuery to dynamically load and assign unique ids to elements within an array

I am seeking assistance with dynamically assigning unique IDs to elements in an array using JavaScript and jQuery. I am new to these languages and need some guidance. function assignIds() { var elementIds = ['name', 'lname', ' ...

Sending a message to an iframe from a different origin using JavaScript

Just starting out with JavaScript and I'm attempting to send a message to my iframe in order to scroll it. Here is the code I am using: scroll(i) { var src = $("#iframe").attr("src"); $("#iframe").contentWindow.postMe ...

Increasing variable in angular template (nested ng-repeat)

I am facing a similar situation as described in the example below, and I need to generate a serial number for each row independently for each mark record. Here is the Java script Object structure: $scope.childsList = [ { id:12346, ...

Encountering a problem with populating data in postgresql

After executing the npm run seed command to populate data into PostgreSQL, even though the seeding process seemed to be successful, I couldn't locate the seeded data in the PostgreSQL database. Can anyone advise on what might have gone wrong or sugges ...

Utilizing Firebase messaging onMessage function is exclusively enabled within a window environment

Incorporating Firebase Cloud Messaging into my project allowed me to send and receive push notifications successfully. While I can receive the push notifications, unfortunately, I am encountering issues with getting the notification events to function prop ...