What is the best way to run a method just once in Vue?

I am in the process of developing a web application that showcases various products (with product details retrieved from the database). Each product is equipped with a More Details >> button which, upon clicking, triggers the opening of a modal window containing specific information about that particular product. However, I have encountered an issue where the allRecords() function in my JavaScript file is being called multiple times, causing excessive activity in the Network tab during inspection. I aim to optimize this by ensuring that the function is only invoked once. While exploring possible solutions, I came across this resource on triggering Vue methods selectively: How to trigger a vue method only once, not every time. I seek guidance on applying similar principles to address this challenge in my code.

Below is the snippet of my code:

PHP FILE

<div id="myapp">
  {{ allRecords() }}
  <div class="content">
    <div class="nested" v-for="product in products">
      ...
    </div>
    <b-modal id="productModal" v-if="chosenProduct" hide-footer="true" ok-title="Buy Now" size="lg" :title="chosenProduct.Name">
      <div class = "inner-container">
        ...
      </div>
    </b-modal>
  </div>
</div>

JS FILE

var app = new Vue({
  'el': '#myapp',
  data: {
    products: "",
    chosenProduct: null
  },
  methods: {
    allRecords: function(){ \\ This function here is being called multiple times
      axios.get('ajaxfile.php')
        .then(function (response) {
          app.products = response.data;
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    chooseProduct: function (product) {
      app.chosenProduct = product
    }
  }
})

Answer №1

As mentioned in my previous comment: To streamline the process, you can make the ajax request within the component's mounted hook. Your callback function is already updating the products property, so there is no need to call {{allRecords()}} from the template. Instead, you can directly utilize the products array in your v-for loop.

Below is a demonstration of this method. I have replaced your PHP code with calls to the 'icanhazdadjoke' API for illustration and entertainment purposes.

var app = new Vue({
  'el': '#myapp',
  data: {
    products: "loading dad joke...",
    chosenProduct: null
  },
  methods: {
    chooseProduct: function(product) {
      app.chosenProduct = product;
    }
  },
  created: function() {
    axios.get('https://icanhazdadjoke.com/search?term=dogs', {
      headers: {
        Accept: 'application/json'
      }
    })
    .then(function(response) {
      app.products = response.results;
    })
    .catch(function(error) {
      console.log(error);
    });
  }
})
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7c6dfcec8d4e79789958996">[email protected]</a>/dist/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="myapp">
  <p v-for="product in products">
    {{product.joke}}
  </p>
</div>

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

Adjust the size of the image to perfectly fit within the div without enlarging it

I have a variety of images with different dimensions, ranging from 50x100 to 4000x4000 pixels. My objective is to display these images in their original size or scale them down to fit within the browser window. However, I have encountered an issue where t ...

How can a function be invoked in a child component from a parent component?

I am facing a challenge where I need to trigger the function showExtraBlogposts() in Blogpostreader.js upon clicking on a button rendered in Blog.js. Initially, I attempted to call it using onClick={Blogpostreader.showExtraBlogposts()} but it returned an ...

The Angular checkbox is not checking in the view despite having a true value in the scope

After clicking "Cancel" in the modal window, the checkbox is unchecked even though it should remain checked (the scope.enabledLogin value is true after pressing the "Cancel" button and dismissing the modal window). Why is this happening? Jade: .checkbox( ...

Issue in CakePHP after modifying the directory of Index

I'm currently working on a project using CakePHP and have come across an issue. Our team developed an Ajax function that sends data to a PHP function responsible for adding a folder (known as "ordner" in German) to the database. Initially, everything ...

Combining two JSON objects into a single JSON object using Jquery/JavaScript

I need to combine two JSON objects into one, here are my current JSON objects: var obj_1 = { "?xml": {"version": "1.0", "encoding": "utf-8"}, "Template": { "Name": "Capital Goods-Tool and Die Maker L5 Set1", "Section": [{ "Id": "Section_ ...

Converting information from an Excel spreadsheet into a JSON format

Looking for a way to extract values from an excel spreadsheet using Python and send them to a webpage for processing with javascript. I'm considering creating a dictionary object and returning it to javascript in JSON format. The values extracted fro ...

Is it possible to send a server response without requiring a callback function to be provided from the client side?

Clarifying the Issue When utilizing .emit() or .send() with a desire to confirm message reception (referred to as acknowledgements), the syntax typically involves: socket.emit('someEvent', payload, callback); The focus of this discussion is on ...

`There was an issue with an unfinished string literal.`

Currently, I am utilizing jQuery to display the information from a JSON string generated by PHP and extracted from a database. However, I have encountered an issue where some of the data spans multiple lines... How can I prevent this from triggering an un ...

Adjusting the color of specific sections within a text box

Can I change the color of a specific section of a text input box? I'm working on a comment widget that needs everything between the @ and : symbols to be in a different color: <input type="text" placeholder="Want To Say Something?" value="@user55 ...

The functionality of AJAX is successful when tested on a local server, but encounters issues when deployed on a live

While the following code functions correctly on localhost, it fails to work on the live server. IMPORTANT UPDATE: There's only 1 issue remaining: Upon successful execution of this AJAX block: $(".FixedDiv").addClass("panel-danger"); setTimeout(c ...

"Troubleshooting: Handling null values in a web service when using jQuery

The API located at http://localhost:57501/api/addDatabase contains the following code snippet: [System.Web.Mvc.HttpPost] public ActionResult Post(addDatabase pNuevaConeccion) { pNuevaConeccion.insertarMetaData(); return null; ...

What location is ideal for making API calls with React and Redux-thunk?

After extensively searching on StackOverflow.com and across the internet, I couldn't find a similar question. Therefore, please refrain from giving negative reputations if you happen to come across one as I truly need reputation at this point in my li ...

Tips for retrieving a variable from an XML file with saxonjs and nodejs

I came across an xml file with the following structure: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE agent SYSTEM "http://www.someUrl.com"> <myData> <service> <description>Description</description> < ...

The art of handling jQuery promises and interconnected AJAX requests

Is there a better way to handle dependent AJAX calls using promises/deferred in jQuery? Currently, my code looks like this: $.when($.ajax('https://somedomain.com/getuserinfo/results.jsonp', { dataType : 'jsonp', jsonp ...

Vue-Router: Identified an ongoing redirection loop in a navigation guard while transitioning from the home page to the login page

I need to implement a feature where pages are blocked if there is no authentication token and users are redirected to the login page. I have two .ts pages (main and routes) routes: import { RouteRecordRaw } from 'vue-router'; const routes: Route ...

I would like to inquire about the process of accessing profile information on a website through the LinkedIn API

Do you know how I can use the latest LinkedIn JavaScript API with OAuth 2.0 to retrieve my own profile details for a website? The goal is to automatically update the website using my linked profile information. I have attempted the following: api_key: ...

What steps can I take to prevent my menu items from overlapping in the mobile navigation menu?

I am currently working on creating a mobile menu, but I'm facing an issue where the menu items overlap when hovered over. Instead, I want the menu items to move downwards when hovered upon to prevent the text from overlapping. Below is the HTML code ...

Retrieving various properties of an object by matching IDs and displaying them without repeated reductions

I'm interested in finding a more efficient way to retrieve properties from a reduced object within a Vue component or wrapper DOM element. Let's say I have these two data objects in my component: player: [{ active: true, id: 0, name: &q ...

Ensure that the second y-axis in charts.js consistently shows the 100% tick

I have implemented a scatter chart using recharts and it currently looks like this: The right-y-axis in my chart represents the percentage and is showing the correct values as desired. However, I am looking to make a modification so that the 100% mark is ...

I am looking for a custom script for a splash page that will automatically redirect users to one of three designated pages based on the information stored

As a programmer, I'm well-versed in coding but lack knowledge about creating and utilizing cookies. If anyone could provide guidance on this matter, it would be highly appreciated. I believe I require two concise scripts for this task. 1st Script: T ...