How to trigger a jQuery function once a v-for loop has completed in VueJS?

Utilizing vue-resource, I successfully retrieve data from my API and incorporate it into my HTML. However, I am encountering an issue where I want to execute a jQuery function after the v-for loop has completed in order for jQuery to recognize elements in my DOM. Here is the snippet of my code:

Javascript

dataUrl = "http://localhost:8081/hesabiha/userSubmissions";

var app = new Vue({
  el: "#campaign",
  methods: {
    getSubmissions: function(){
      this.$http.get(dataUrl, function(submissions){
        this.$set('submissions', submissions);
      });
    },
  },

  ready: function(){
    this.getSubmissions();
  }
});

HTML

<div v-for="item in submissions" class="grid-item">
    <img v-bind:src="item.field_image[0].url" alt="Hello">
</div>

I am attempting to trigger this function on my page:

$('.grid').masonry({
    // options...
    itemSelector: '.grid-item',
    columnWidth: 200
  });

Unfortunately, it seems that the function is not working as intended. Is there a way to ensure that this jQuery function runs only after the v-for loop has completed?

Answer №1

Experiment

fetchData: function(){
  var _self = this
  this.$http.get(dataUrl, function(feed){
    this.$set('feedData', feed);
    this.$nextTick(function(){/*execute when the DOM is fully loaded*/})
  }
}

Answer №2

When using the v-for directive in Vue, it interacts with the life-cycle hooks of the component. During the initial render of Vue on the DOM, v-for does not take effect. Instead, it works during the update phase of the DOM. Therefore, any functions placed after the updated hook will be executed after v-for.

enter code here

methods:{
},

updated({
//your code
}

Answer №3

dataUrl = "http://localhost:8081/hesabiha/userSubmissions";

var application = new Vue({
  el: "#campaign",
  methods: {
    fetchUserSubmissions: function(){
      this.$http.get(dataUrl, function(submissions){
        this.$set('submissions', submissions);

        $('.grid').masonry({
            // options...
            itemSelector: '.grid-item',
            columnWidth: 200
        });
      });
    },
  },
  ready: function(){
    this.fetchUserSubmissions();
  }
});

In case the above code does not execute successfully, consider invoking the .grid functionality after a brief timeout period.

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

Dynamic Namespaces in Socket.io is a feature that allows for

I am currently working on implementing multiple namespaces in my app. As I receive route parameters, I dynamically create new namespaces. For example: var nsp = io.of('/'); var className; app.post('/class/:classID',function(req,res){ ...

How can I efficiently extract specific data from JSON using AngularJs?

In my array (_users), there are JSON objects. { "User": { "userid":"19571", "status":"7", "active":"1", "lastlogin":"1339759025307", "Stats": [ { "active":"1", "catid":"10918", "typeid":"71", ...

attach an event listener for the click event

I have a button set up like this Inside index.html: <body> <section> <button id="open-file">Open File</button> ...(series of other similar buttons)... </section> </body> <script> requir ...

Swapping out image sources using a React Hook that includes an onClick event

Despite my best efforts, I have yet to find a solution to this problem. To keep things brief, I am attempting to implement a dark mode toggle in my React application, but my current method feels like a hack. The main issue I am facing is changing the imag ...

Is it not odd that there are two '=>' symbols in an arrow function when there is typically only one? What could this possibly signify?

function updateStateValue(name) { return (event) => { setState({ ...state, [name]: event.target.checked }); }; } To view the full code example, visit CodeSandbox. ...

jQuery mobile : accessibility helper for hidden elements

Within my HTML structure: <div data-role="fieldcontain" id="containdiv" class="no-field-separator"> <label for="field1" class="ui-hidden-accessible">To</label> <input type="search" name="field1" id="field1" autocorrect="off" a ...

Iterate through JSON objects

Having an issue with looping through JSON using jQuery AJAX. Despite receiving the JSON data from PHP and converting it to a string, I'm unable to loop through it properly in JavaScript. In my for loop, I need to access $htmlvalue[i] to parse the data ...

having difficulty obtaining the keyCode/key event while input event is triggered

Recently, I encountered a challenge where I attempted to log the event key during an input bound event on the input. Below is the code snippet of what I tried: <div id="app"> <input @input="onInput" @keyup="onKeyUp" type="text"> </div&g ...

Arranging and structuring Handlebars templates

In this particular example... http://example.com/1 ...I am experimenting with organizing a Handlebars template and its corresponding content in separate files, as opposed to having them all combined in the HTML file or JavaScript script, like in this con ...

The Google Javascript API Photo getURL function provides a temporary URL that may not always lead to the correct photo_reference

Currently, I am integrating Google Autocomplete with Maps Javascript API into my Angular 5 application. As part of my website functionality, I fetch details about a place, including available photos. The photo URL is obtained through the getURL() method. ...

Combine strings in an array of objects

I have an array containing objects with a "Closed" property that holds numerical values. I want to loop through the array and concatenate all the "Closed" property values found in each object. For example, in the given array, the final result should be 12 ...

Best method for connecting user input with a class

I'm currently working with a WYSIWYG editor (Tinymce) that allows users to post YouTube videos. In order to make the video content responsive, I need to add the class "video-container" around any "iframe" tags inserted when users paste a YouTube link ...

Encountering the error message "require is not defined" in the browser while utilizing gulp-browserify for my React.js modules

I am currently working on using gulp-browserify for creating a bundle.js file that will be utilized in the client's browser to initiate rendering of React components. Below is my App.js file: /** @jsx React.DOM */ var React = require('react&apo ...

Choosing an automatically generated choice from a C# web browser control

Using a c# web browser control, I am navigating a commercial website to access a list of potential jobs. However, I encountered an issue while trying to bid on these jobs through some links. The problem arises when dealing with forms that contain two sele ...

What is the best method for storing a client-side token in nextjs 13 with the App Router update?

We are currently using a nextjs 13.5 web application. The new app router paradigm in Next.js 13 involves all components, including client components, going through their initial render on the server during a full page load (such as after a refresh). Accord ...

The function(result) is triggered when an http.get request is made

Can anyone help me figure out why my function is jumping after completing the request? It seems to be skipping over .then(function(result){ }. I suspect that the issue might be related to the <a> element with an onclick attribute containing an href ...

What could be causing my function to output unicode replacement characters instead?

As I work on enhancing password security by implementing encryption, my goal is to store the hashes and perform encryption/decryption during signup/login processes. The encryption process works smoothly, converting from utf8 to hex without any issues. Howe ...

Reference Error occurs in Vue unit test due to third party dependency issue

I have a very simple Vue component: <script> export default { name: "simpleComponent", data() { return { manageWaiting: new ManageWaiting() } } } </script> Trying to t ...

Is jquery.validate showing errors more than once?

For my testing program, I utilize the jquery.validate plugin to validate user input fields. Here is how it's set up: <script src="js/jquery-1.12.4.min.js"></script> <script src="js/jquery-form-3.51.min.js"></script> <script ...

Generate real-time dynamic line charts using data pulled directly from a MySQL database

I am in search of guidance on developing a real-time line chart that can dynamically update based on data fetched from MySQL. I need an example or reference on how to achieve this functionality without having to refresh the webpage every time new data is ...