The Mounted method in Vue.js does not seem to be firing when I utilize a computed method to filter components

I have a requirement to showcase an image obtained from an external API. The image fetching logic is implemented in the mounted hook of my ProductCard.vue component.

<template>
  <q-card
    class="my-card column text-center no-border-radius"
    flat
    bordered
  >
    <q-img
      :src="PRODUCT_IMG_SRC"
      sizes="(max-width: 400px) 400w,
              (min-width: 400px) and (max-width: 800px) 800w,
              (min-width: 800px) and (max-width: 1200px) 1200w,
              (min-width: 1200px) 1600w"
      loading="eager"
    />
    <q-card-section>
      <div class="text-caption text-grey text-left">
        {{ truncate(product.description, 100) }}
      </div>
    </q-card-section>
  </q-card>
</template>

<script lang="ts">
import { defineComponent, onMounted, ref } from 'vue';
import { truncate } from 'src/utils/textUtils';
import fallback_image from 'src/assets/dluhopis_houses_responsive.svg';

export default defineComponent({
  name: 'ProductCard',
  props: {
    product: Object,
    chosen: Boolean,
  },
  setup(props) {
    const PRODUCT_IMG_SRC = ref();

    onMounted(async() => {
      const IMG_URL = `https://ydc.datanasiti.cz/api/product/${props?.product?.externalId}/image`;
      const response = await fetch(IMG_URL);


      if (response.status === 200) {
        return (PRODUCT_IMG_SRC.value = IMG_URL);
      } else {
        PRODUCT_IMG_SRC.value = fallback_image;
      }
    });

    return {
      truncate,
      PRODUCT_IMG_SRC,
    };
  },
});
</script>

In the parent component, I use a v-for loop to render this child component based on the computed property PageProducts, which filters products per page.


<template>
  <div
    v-if="pageProducts"
    :class="[productChosen ? '' : 'row items-stretch q-col-gutter-x-md']"
    class="q-pb-md wrap"
  >
    <template v-if="!productChosen">
      <div
        v-for="(product, index) in pageProducts"
        :key="`md-${index}`"
        class="col-sm-5 col-md-4 col-lg-3 col-xl-2 q-mt-md justify-sm-center flex"
      >
        <product-card
          :product="product"
          @product-detail="toggleDetail"
          @choose-product="chooseProduct"
        />
      </div>
    </template>
    <div
      class="q-pa-lg flex flex-center col-12"
    >
      <q-pagination
        v-if="!productChosen"
        v-model="currentPage"
        :max="pagesCount()"
        direction-links
      />
    </div>
   
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, reactive, ref, toRefs, computed } from 'vue';
import ProductCard from 'src/components/ProductCard.vue';
import { products } from 'src/api/api';
import { AxiosResponse } from 'axios';
import useDate from 'src/utils/useDate';
import { useQuasar } from 'quasar';
import { IProduct, PAYOUT_FREQUENCY } from 'src/interfaces/Purchase';


// Component definition...
</script>

The issue I encountered is that the mounted method in the child component ProductCard.vue is not called for every product when the computed property changes in the parent component. It seems to only trigger for the first 8 products and then again when navigating between certain pages. This behavior is puzzling.

Any insights into why this occurs or suggestions on how to improve this behavior?

Answer №1

Building on my previous message, in cases where the items being passed to your template through a loop (v-for) are dynamically changing – for example, due to pagination – and you require a complete component re-render, it is essential to use keys to notify Vue that the reactive property has been modified and prompt the component to refresh entirely.

<product-card
  :product="product"
  @product-detail="toggleDetail"
  @choose-product="chooseProduct"
  :key="product.id"
/>

Answer №2

As a component in Vue mounts, it only executes once as part of the component lifecycle. Subsequently, Vue's reactivity system dynamically updates the DOM when reactive data is modified. Therefore, it is correct that your #mounted hook is triggered only once.

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

Imitate the moment() function with jest

I am attempting to simulate the behavior of moment() in order to prevent a snapshot test from failing due to the time of day. Within my <Header /> component, there is a function that utilizes moment() to display various greetings (Hello, Good morning ...

Failure to refresh Polymer element attribute detected in lit web component

Recently, I've been diving into the world of the Home Assistant project's usage of Polymer app-layout elements combined with the Lit library. However, I've hit a roadblock where I can't seem to update a public property in my custom comp ...

Replicating an array of typed objects in Angular2

I have a collection of specific object types and I'm looking to duplicate it so that I can work on a separate version. In order for the configuratorProduct to function correctly, I need to provide it with a copy of the listProducts values: listPro ...

Building a dynamic webpage using AJAX, MVC, and web APIs to generate a div element filled

I'm currently working with a restful API, MVC, and ajax. My goal is to retrieve data from the backend and then display images within certain div elements. The expected outcome should resemble this example: https://i.stack.imgur.com/BFqWL.png This sni ...

Dynamically assigning classes based on the element that is being scrolled beyond

I am working on a navigation bar (nav) that consists of letters and corresponding sections. My goal is to add an active class to the letter when a user scrolls to its associated section. For instance: When the user scrolls to a section with the id of a, t ...

Make sure to refresh the state of the store whenever there is a change detected in the input

I am experiencing an input delay problem when trying to update the state of a zustand variable in the onChange event. const BuildOrder = (props: { setOpen: Function }) => { const { almacenes, isLoadingAlmacenes } = useGetAlmacenes(); const { article ...

Assign a unique variable to each div simultaneously

I am looking to implement a countdown feature for each DIV with the class (.topitembox) by incorporating specific JSON variables. $('#countdown_items .topitembox').each(function () { itmID = $(this).attr('class').replace(/[^0-9]/g, ...

Tips for resolving asynchronous s3 resolver uploads using Node.js and GraphQL

My goal is to upload an image and then save the link to a user in the database. Below is my GraphQL resolver implementation: resolve: async (_root, args, { user, prisma }) => { .... const params = { Bucket: s3BucketName, ...

Button that triggers HTML Audio play when clicked

Is it possible to have audio play when Button 1 is clicked, but then pause or stop if Buttons 2 or 3 are clicked instead? <a href="#" class="button1">Button 1</a> <a href="#" class="button2">Button 2</a> <a href="# ...

Using nuxt-link with a configuration variable passed as the query parameter key

I am seeking a method to pass an environment configuration variable called process.env.config.myVar to my nuxt-link like this: :to="{ name: 'search-page', query: { process.env.config.myVar: { query: `${searchValue}` } } }" My ...

Various <a> elements adjust the HTML code based on the selected option

I am working with the following code snippet: <!-- LANGUAGE --> <div class="languages_box"> <span class="red">Languages:</span> <a href="#" class="selected"><img src="../images/au.gif" alt="" title="" border="0" he ...

Class Chat Practice Application

I'm a beginner in the world of programming and I could really use some assistance with troubleshooting my ChatApp. My goal is to have my server send the message "Robot: (client's username) connected" whenever someone logs on. I've been gra ...

Steps for including a map in a property file for JavaScript parsing

When a checkbox is clicked, a new series of checkboxes will be displayed. The details for these checkboxes are fetched from a database. However, I now need to have certain checkboxes pre-checked based on the user's selection. Since I can't store ...

Using Vue.js for redirecting with a post method

Is there a way to redirect from Vue.js to a Laravel controller using the POST method without using AJAX? I would like to be able to use var_dump or dd inside the controller. //Vue.js axios.post('/add-hotel-listing', this.finish).then((respons ...

Moving a DIV below a fixed-positioned element

I have a website with a scrollable div. It works well, but I also need an absolutely positioned div on top of it - and it still needs to scroll smoothly without any hindrance. You can check out a basic JSFiddle demonstration here: http://jsfiddle.net/41ra ...

How can I design unique navigation menus using HTML, CSS, JavaScript, and jQuery?

Is there a way to create menus where clicking on a holiday/seasonal category opens up all related lists automatically? For example: https://i.sstatic.net/Nctd1.png I've been searching online for submenu options but haven't found the right metho ...

AngularJS: dependent dropdown menus

Attempting to create a cascade dropdown in Angular, I assumed it would work seamlessly with binding. Here is the code snippet: <select name="client" ng-model="selectedRequest.client" ng-options="c.name for c in clients track by c.id" req ...

Using `appendChild` in combination with `createElement`

Is there a difference between these two approaches: var div = document.createElement('div');//output -> [object HTMLDivElement] document.getElementById('container').appendChild(div); and: var div = '<div></div>&a ...

Extract data from the HTML source code in JavaScript and transfer it to a personalized JavaScript variable within Google Tag Manager

Running an e-commerce website on Prestashop and facing an issue with data layer set up. Instead of a standard data layer, the platform generates a javascript variable called MBG for Enhanced E-Commerce implementation. <script type="text/javascript"> ...

Can you explain the distinction between using "require" to return a module and accessing the actual object in node.js?

When working with node.js, the commonly used method to include modules from other files is by using "require", whether it's from our own code or third-party libraries. But for me, there seems to be some confusion regarding the distinction between the ...