A new Vue component is regenerated after the creation method is called

I am facing an issue with setting the margin of an image to display it in the center of the page when the image dialog is created. I have calculated the margin in the component's created method and everything seems fine during debugging as the image is positioned correctly after using my jquery margin set method. However, as I continue debugging, the component is somehow rerendered without accessing the created method again, resulting in the image margin not being set. This situation occurs whenever I try to set a variable in the created method as the component frequently rerenders without going into the created block. Is there any solution to prevent this continuous rerendering? It is quite frustrating.

This is the code snippet from my created block :

async created() {
    let self = this;

    $('.vodal.image-dialog').css('cursor', 'wait');

    $('.vodal.image-dialog').css('cursor', 'default');
    var margin = $(window).width() / 2 - $(".vodal.image-dialog .pop-up img").width() / 2;
    $(".vodal.image-dialog img").css('margin-left', margin);
    $(".vodal.image-dialog .pop-up img").show();

  },

UPDATE :

To address this issue, I found a solution by utilizing the v-bind:style attribute to set the margin and retrieving it from a computed property like this :

<img v-if="isEntitySaved()" v-bind:style="{'margin-left': margin + 'px'}"
      v-bind:src="image" class="blurred"/>
...
computed: {
    margin: function() {
      var imgClass = ''
      if(this.source == 'detail-main')
        imgClass = ".vodal.image-dialog .pop-up .main-image img"
      else
        imgClass = ".vodal.image-dialog .pop-up .side-image img"

      return $(window).width() / 2 - $(".vodal.image-dialog .pop-up ." + this.source + " img").width() / 2
    }
  }

However, the problem persists in another component where the template style is initially set to 'display: none'. Upon clicking a button, I want to display the component by changing its style to 'display: block' in both the created and updated methods. Despite showing up briefly after the $.show method at the end of the created block, the component gets rerendered and disappears without accessing the created or updated block. How can I resolve this issue?

Answer №1

created method is only executed once; consider using the updated method instead.

export default {
  created() {
    this.updateStyle();
  },
  updated() {
   this.updateStyle();
  },
  methods: {
    updateStyle() {
      let self = this;

      $(".vodal.image-dialog").css("cursor", "wait");

      $(".vodal.image-dialog").css("cursor", "default");
      var margin =
        $(window).width() / 2 -
        $(".vodal.image-dialog .pop-up img").width() / 2;
      $(".vodal.image-dialog img").css("margin-left", margin);
      $(".vodal.image-dialog .pop-up img").show();
    },
  },
};

Enhancement

It seems that you are relying heavily on jQuery within your Vue app.

To address this, you could trigger a re-render by incrementing a count variable like so:

export default {
  data() {
    return {
      count: 0,
    };
  },
  updated() {
    // Ensure that updated is triggered whenever this.count changes
  },
  methods: {
    doSomething() {
      // Perform your desired actions here
      // .......
      // Once done, increment the count to trigger an update
      this.count++;
    },
  },
};

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

Incorrect variable value retrieved in AJAX callback

I am working on a code that utilizes JSON to validate VAT numbers. My main goal is to identify which VAT numbers are valid BTW[0] = 'NL1234567890'; BTW[1] = 'NL1233537891'; BTW[2] = 'NL1232346894'; var arraylength = BTW.leng ...

What is the best way to pass JavaScript object literals from a Node.js server to the frontend browser?

In Node, I am working with JavaScript object literals containing methods in the backend. For example: const report = { id: 1, title: 'Quarterly Report for Department 12345', abstract: 'This report shows the results of the sales ...

Obtain the maximum or minimum value from an associative array using a function and provided parameters

Here is the code I have so far: <!DOCTYPE html> <html> <body> <button onclick="scanarray('a', 'max')">Test with a, max</button> <button onclick="scanarray('b', 'min')">Test with ...

Guide to creating individual column templates in Kendo-UI grid

I recently started using Kendo-UI in my project and wanted to have a column in my grid display an image button along with a field, similar to the 'Contact Name' column in the documentation here. After exploring the documentation, I came across th ...

To enhance user experience, consider incorporating a 'Next Page' feature after the completion of every four paragraphs,

Here is a code snippet that can be used to print 'n' number of paragraphs: <% while(rs.next()){ String para=rs.getString("poems"); %> <p> <%=para%> </p> <!-- n number of p tags are printe ...

Acquire JSON information from PHP utilizing JavaScript

I am a beginner with JSON and I'm retrieving data from PHP code in JSON format. [ { "Title": "New Event", "TYPE": "info", "StartsAt": "16 November 201512:00", "EndsAt": "25 November 201512:00" }, { ...

The Vue3 property 'x' is not recognized on type 'Function' as a global property

I have encountered a strange issue with my Quasar app. I am attempting to define a global variable that consists of metadata about the application in an object format. Despite successfully compiling the app and displaying the correct information on the HTM ...

What are the steps for creating an animated visualization of the peak chart?

As a newcomer to CSS and Javascript, I am currently struggling with animating a peak (bar) chart that I came across on codepen. If anyone can provide assistance or guidance, it would be greatly appreciated! The chart can be found here: http://codepen.io/An ...

How can I restrict the navigation buttons in FullCalendar to only allow viewing the current month and the next one?

I recently downloaded the FullCalendar plugin from Is there a way to disable the previous button so that only the current month is visible? Also, how can I limit the next button so that only one upcoming month is shown? In my header, I included this code ...

Fetch solely the metadata from HTML5 video and audio files

Before we dive in, let me address a question I have regarding video metadata loading without any additional video content. The preload = "metadata" attribute doesn't seem to be functioning as expected. My testing thus far has been limited to Win Chrom ...

Tips for writing unit tests for components using vitest in the latest version of Nuxt

I've been working on transitioning from Vue 3 to Nuxt 3. I've successfully written unit tests for my components using vitest in my Vue app, however, when running the same tests in the Nuxt app, I encounter the following error: Error: Failed to ...

Perform a task only once during several scroll events and disable additional scrolling

I want to add scrolling functionality similar to the Google Inbox landing page: On that page, no matter how fast or how many times you scroll the wheel, it only counts as one scroll and moves to the next step. This sounds simple, but it's actually qu ...

HTML5 Slideshow with Smooth Image Transitions

So, I have created an HTML5 image slideshow and it's working perfectly on my localhost. However, I am puzzled as to why there is no transition effect within the slideshow. I was expecting something like fading out the first picture and then having the ...

Retrieve error messages from API while utilizing Next-auth

Is it possible for Next-auth to handle API errors and pass them to the client-side? For example, our mobile app successfully handles API responses indicating incorrect email or password. However, on our website using Next-auth, we want to modify the retur ...

`problem encountered when attempting to sanitize HTML through the npm package known as "sanitize-html"`

After researching the documentation, I attempted to use this code snippet: const dirty = '<div>Content</div>'; const clean = sanitizeHtml(dirty); The desired result of 'clean' should be "Content", however it seems that &apo ...

Resolving issues with setting up d3.js in the 'Creating a Custom Map' guide

Starting Mike Bostock's tutorial on creating a map, but facing some installation issues at the beginning. I am using Windows 8.1 for this. This is the specific part that's causing trouble: "To get started, you'll need the reference implemen ...

Issue: Encounter an Error with Status Code 401 using Axios in React.js

For my login page, I am utilizing a combination of Laravel API and ReactJS frontend. In my ReactJS code, I am using Axios to handle the parsing of the username (email) and password. The login API endpoint is specified as http://127.0.0.1:8000/api/login, wh ...

Ways to modify CSS using JavaScript

Can anyone assist me with a custom CSS code that I found? It looks like this: header.type-2:not(.fixed-header) nav>ul>li>a{ color:#000; } I've been trying to change the color to #fff using JavaScript, but haven't had any success yet. ...

Creating a Client-side Web Application with Node.js

As I search for a versatile solution to bundle an HTML5 web application (without server dependencies) into a single executable app using node.js and the Linux terminal on Ubuntu, I have experimented with tools like wkpdftohtml and phantomjs. However, these ...

What is the process for configuring the Sequelize Postgres model type to inet in a database?

I have been utilizing the sequelize ORM to manage my postgress database. Within my postgress database, we have been using the inet data type to store IPv4 and IPv6 values. While creating models in sequelize, I encountered the issue of not finding the ine ...