How to adjust the width of nested divs in Nuxt.js/Vue.js to align with a specific container in the stack

Is there a way to handle varying image widths in Nuxt without compromising the layout? I have an image component that needs to adjust for different screen sizes, and I want the title and description to always match the width of the image. Here's what I currently have:

<div>
  <h2 >{{insightsImage.title}}</h3>
  <img :src='ifMobile ? mobileImage.url : image.url' />
  <p>some text</p> 
</div>

I'm looking for a more efficient solution, possibly using just CSS, but so far none have worked with variable image widths.

This is my current workaround:

<div>
  <h2 :style='`max-width: ${imageSize}`'>{{insightsImage.title}}</h3>
  <img :src='ifMobile ? mobileImage.url : image.url' />
  <p :style='`max-width: ${imageSize}`'/>some text</p> 
</div>


export default defineComponent({
  computed: {
    imageSize(): string {
      if (!process.browser) return ''
      const image = new Image();
      image.src = this.image.url;

      return `${image.width > 0 ? image.width : 800}px`
    }

I've explored various solutions, but haven't found a perfect one yet. Any recommendations on how to approach this?

I considered using refs like this: Using $refs in a computed property

However, the official docs advise against abusing refs in computed props. Plus, the computed width doesn't update when the image source changes. Any other ideas?

Answer №1

Just wanted to share my solution in case it helps someone else. I was facing an issue with inline styles, but I found a workaround that works for me. The original solution didn't always work as expected, especially when the image size was 0 upon routing to the page. After experimenting a bit, I discovered that using vue's Mounted/Updated lifecycle hooks along with image.onload helped me keep track of the image width during screen resizing. Here is how I implemented it:


<div>
  <h2 :style='`max-width: ${imageSize}`'>{{insightsImage.title}}</h3>
  <img :src='ifMobile ? mobileImage.url : image.url' />
  <p :style='`max-width: ${imageSize}`'/>some text</p> 
</div>

export default defineComponent({
 data() {
    return {
      imageSize: ''
    }
  },
  updated() {
    this.updateImageSize()
  },
  mounted() {
    this.updateImageSize()
  },
  methods: {
    updateImageSize() {
      const vm = this
      const image = new Image()
      image.src = this.image.url
      image.onload = function() {
          vm.imageSize = `${image.width}px`
        }
      }
    }
  }
})

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

What is the best way to implement a "param" feature similar to React's onChange and onClick methods?

I am interested in replicating the functionality of React's onClick, onChange, etc. An example of how React does this is: onClick={(event)=>console.log(event)} My goal is to achieve a similar effect using my custom property: someProp={(wanna_do_t ...

A picture placed side by side with a list

Could someone please help me figure out what I'm doing incorrectly? <div class="row"> <ul class='list-group .col-md-6'> <li>1</li><li>1</li><li>1</li> </ul> <div> ...

AngularJS controller exceeding allowed complexity (SonarLint alert)

While utilizing SonarLint in Eclipse, I encountered an issue while working on an AngularJS application. Specifically, I was cleaning up a controller to improve readability when SonarLint flagged the following problem: The function has a complexity of 11 ...

Receiving blank response when trying to access server variable on the client side

Query: On the server side, I set the value of SessionData(EmployeeID) = "12345", which is first executed during page_load. Later, on the client side: function getEmployeeId() { return "<%# SessionData("EmployeeID")%>"; } When I use th ...

Trouble with the display none function

I am trying to achieve the following: If my shopping cart is empty, I want another div to display over the top of it. Instead of seeing the cart, users should see a message saying 'your cart is empty'. Currently, I have set the other div to dis ...

Jquery oscillation effect

I am attempting to create a seesaw effect using jQuery, but I'm unsure about which plugin would be best for this task. The goal is to have the bar move up and down while the box on top moves in sync with it. You can find my code on JsFiddler here: htt ...

How can one transform an array (in the form of a JSON array) into a map?

After running my script, I receive an array (JSON Array) structured like this: [{redirectCount=0, encodedBodySize=60962, unloadEventEnd=0, responseEnd=1601.699999999255, domainLookupEnd=995.7999999896856, ... Now, I want to display the key-value pairs fr ...

Masked input fails to accurately capture data

When utilizing VueJS together with the Quasar framework. An issue arises when using a masked q-input, where the value becomes incorrect after a toggle. For instance, if we start with a default value of: officeNum: 654321, mobileNum: 12345678, Then our ...

Sending a blob through AJAX to a different domain using CORS

Could someone please explain why my current request is being blocked by the SO policy restriction? Javascript Code: var blob = new Blob([req.response], {type: "application/octet-stream"}); req = new XMLHttpRequest(); req.open("POST", ws_path(other_contex ...

Apply CSS to every other div using a CSS selector

Struggling with selecting specific divs in CSS. Snippet of my code: <div class="card"> <div class="test">Asdasdasd</div> </div> <div class="card"> <div class="test">Asdasdasd</div> </div> <div class= ...

Is there a way to utilize JSON parse for converting deeply nested keys from underscore to camelCase?

A JSON string containing an object is on my mind: const str = `[{"user_id":"561904e8-6e45-5012-a9d8-e2ff8761acf6","email_addr":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="caa0a3a6a5bc8aaca ...

Increasing the size of iframe in a Flexbox layout

I'm facing a challenge in making the iframe element stretch to occupy the remaining space within my web application. While I have ensured that the maximum space is allocated for the div by setting a border, the iframe's height does not automatica ...

DataGrid Filtering with Material-UI

I recently started working on a React project and I'm trying to incorporate the mui datagrid component. I want to include filters for '>' and '<', but I couldn't find any information in the documentation. Is there a spec ...

When an action is dispatched, Vuex modifies two elements within the state

I am encountering an issue with my Vuex store in a Vue2 and Vuex2 setup. Upon dispatching a specific action, it alters the state of 2 elements in my store. Here's a snippet of the state with some dummy data for clarity: { "clients":[ ...

What is the method to define a function in express js that is accessible from all views?

Is there a way to develop a function within my Express JS MVC web application that can be accessed from any view? How can I define this function in middleware so it can be directly called from a view? I envision being able to use this function like: < ...

Changing the height of the parent div in Angular 2 to match the height of the child div that holds an image

When I make an HTTP call to fetch a block of HTML from an external source, the structure of the retrieved HTML looks like this: <div class="container"> <div class="wrapper"> <div class="image"> <img src="img_url> ...

Validation of input using JQuery

I am currently working on validating a form, with a specific field that needs to be required. Here is the code for the field in question: <p> <label for="lf">Name: </label> <input class="lf" name="name" type="text"/> < ...

What methods can be used to block the input of non-numeric characters in a text field?

I stumbled upon this particular inquiry. Although, the majority of responses involve intercepting key presses, checking the key code, and halting the event if it does not match an acceptable key code. However, there are some issues with this approach. ...

Vue.js watcher doesn't get triggered when value is manually assigned

I'm currently working on a Vue component that looks like this: methods: { ... toggleTyping: function () { this.composing = !this.composing; }, ... }, data: function () { return { composing: false, }; }, watch: { composing: funct ...

"Adding a Vue component into a contenteditable div: A step-by-step guide

Looking to develop a simple wysiwyg editor with Vue, I came across only one fully-fledged wysiwyg editor built on vue.js at https://quasar.dev/vue-components/editor. However, I couldn't find the ability to insert images there. Most other Vue wysiwyg e ...