Vue - making one element's width match another element's width

Trying to dynamically adjust the innermost element's width to match the outermost element's width with Vue:

<div id="banner-container" class="row">
    <div class="col-xs-12">
        <div class="card mb-2">
            <div class="banner banner-tag card-body" :style="getBannerStyle"></div>
        </div>
    </div>
</div>

Here is the relevant Javascript code and Vue computed property logic:

var container = document.getElementById('banner-container').offsetWidth;
...
computed: {
    getBannerStyle () {
        return 'width: ' + container + 'px;';
    }
}

Answer №1

getBannerStyle will not be reactive if it does not access any other reactive properties. To make it reactive, you should assign the offsetWidth value to a data property and reference that within getBannerStyle. You can achieve this by adding the following code:

mounted () {
  this.offsetWidth = document.getElementById('banner-container').offsetWidth
},
data () {
  return {
    offsetWidth: 0,
  }
},
computed: {
    getBannerStyle () {
        return `width: ${this.offsetWidth}px;`
    }
}

Answer №2

Regrettably, achieving this in pure Vue can be extremely challenging because the element might not have a size during any of the lifecycle hooks, particularly if it's not immediately visible on page load. Thankfully, all modern browsers come equipped with a handy class that can assist: ResizeObserver.

data: () => ({
    offsetWidth: 0,
    resizeObserver: null
}),
mounted() {
    this.resizeObserver = new ResizeObserver(this.onResize)
    this.resizeObserver.observe(document.getElementById('banner-container'))
    this.onResize()
},
beforeUnmount() {
    this.resizeObserver.unobserve(document.getElementById('banner-container'))
},
methods() {
    onResize() {
      this.offsetWidth = document.getElementById('banner-container').offsetWidth
    }
}

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

Include a photo in the notification when utilizing the sendToTopic function

I am looking to utilize the sendToTopic method for sending notifications to a topic. Is there a way to include an image in the notification? It seems that notification.imageUrl is not available as an option. ...

Trouble arises from duplicating custom SCSS code while making modifications to SaaS variables in vue.config.js

My goal is to create a structure for overriding Vuetify variables values. However, I am facing an issue where the custom scss files with custom classes that I import end up being repeated multiple times - 92 times to be precise. I have successfully overri ...

Is it advisable to disregard mutation handlers in Vuex and consistently modify the store data directly?

When opting to directly mutate store data without using mutation handlers, you may find yourself writing significantly less code compared to following official guidelines that require computed properties and store mutations for nested state properties. In ...

Guide to creating a v-autocomplete that displays items starting with the search term first, followed by items containing the search term

I am working on implementing a vuetify autocomplete feature with a custom filter that prioritizes showing search results starting with the search text before displaying those where the search text appears in the middle of the result. Currently, my custom ...

Exploring the getJSON function within jQuery

{ "Emily":{ "Math":"87", "Science":"91", "Email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1d6f7e767c51767b727e737f764f747879">[email protected]</a>", "City":"Chicago" }, "Sa ...

Show a pop-up form when a user focuses on it using React

Hello, I have been looking for a way to create an overlay with a form that appears when a specific input field is clicked. I am trying to achieve this using React. Can someone please advise me on how to accomplish this? Here is my code import React, { Co ...

Unlocking the Power of Vue 3 Composition API for Section Rebuilding

In my project, there is a file named CreateSales.vue which is incorporated in Layout.vue. In CreateSales.vue, a specific code snippet loads when the file is executed, shown below: <FormModal v-if="processingData" :processingData="processi ...

The content of the string within the .ts file sourced from an external JSON document

I'm feeling a bit disoriented about this topic. Is it feasible to insert a string from an external JSON file into the .ts file? I aim to display the URLs of each item in an IONIC InAppBrowser. For this reason, I intend to generate a variable with a sp ...

I am interested in utilizing angular 4 ng2-ui/map with places-auto-complete functionality that is restricted to a specific country

Check out my code snippet below: <input class="form-control" placeholder="Pickup Location" places-auto-complete (place_changed)="pickupChanged($event)" formControlName="pickup_location" [types]="['geocode']" /> I am trying to figure out ...

Unusually Elevated Frame Rates within Three.js

I just launched a new website yesterday, which is dedicated to live editing three.js examples. I noticed that whenever I make updates to the code or switch between different example files, the frame rate of the site jumps up to around 1000 f/s. You can fi ...

Encountering a Next.js application error while utilizing the button tag in conjunction with generating metadata

I keep encountering an issue with generateMetaData when trying to utilize the button tag. Can you help me resolve this problem? Currently, I am working with nextjs and I am unable to properly use the <button> tag. Whenever I implement generateMetaD ...

Bringing a React Context Back to its Original State

The default state of a React Context is defined as: export const defaultState: UsersState = { isModalOpen: false, isCancelRequest: false, companyId: 0, users: [] }; After cancelling the modal, the goal is to reset the state back to its default va ...

Avoid nesting ternary expressions when possible - consider alternative solutions

I am currently working on a React component that has 4 different states: advisoryResults, results, noResults, and newAccount. While I initially thought about using a ternary expression for this, it turns out that it is not allowed in this case. Can you su ...

The method for organizing boxes on the stack exchange website's list page

I can't help but wonder about a unique and innovative feature on this stackexchange page that showcases all the stackexchange sites in a grid layout. Upon clicking on a site box, it expands in size while the surrounding boxes adjust their positions t ...

Is there a better approach to verifying an error code in a `Response` body without relying on `clone()` in a Cloudflare proxy worker?

I am currently implementing a similar process in a Cloudflare worker const response = await fetch(...); const json = await response.clone().json<any>(); if (json.errorCode) { console.log(json.errorCode, json.message); return new Response('An ...

Different scenarios call for different techniques when it comes to matching text between special characters

I encounter different scenarios where strings are involved. The goal is to extract the text in between the || symbols. If there is only one ||, then the first part should be taken. For example: Useless information|| basic information|| advanced informa ...

What is the best way to focus on an object using a particular variable in javascript?

I am currently developing an online game where each user is assigned a unique ID. Below is the client code used to create a new player: const createNewPlayer = (id) => { return player[player.length] = { x:0, y:0, id:id } } The ...

Leveraging react-markdown alongside Material-UI's table component

Currently, I am attempting to parse a markdown table using the react-markdown library and then displaying the resulting tags with the help of the Material-UI table component. Below is the code snippet for my renderer: import withStyles from '@material ...

Displaying AJAX data in a table format, showcasing 10 rows of information

I am currently working on an ajax function that retrieves data from a database based on the entered information. My goal is to display this information in a table with the following format: System Id | Last Name | First Name | Middle Name | Address Below ...

Using a third-party Vue component within a .NET Core Razor Page, such as Vue Cal, can be easily achieved by following these steps

Greetings esteemed individuals of Stack Overflow. I am currently experimenting with the combination of .NET Core Razor Pages and the VueJS JavaScript framework. I'm interested in utilizing the Vue Cal library to showcase a calendar view on my Razor P ...