Error in VueJS when attempting to call a method within a v-for loop: 'not defined on the instance but referenced during render'

I’m still getting the hang of Vue.js (Vuebie?), and while I know this question has been asked before, I’ve not quite stumbled upon a solution myself.

My current challenge involves passing an object to a method in order to increment a value and then display the total value.

Every attempt I’ve made so far results in either a

method / prop not defined on instance but referenced during render
error or various undefined variable errors.

This particular template is deeply nested within other templates, which leaves me uncertain about how or where to properly define my getCollectionsTotal method.

<template>
  <div>
    <ul class="c-filter__list" v-if="categories.length">
      <li
        class="c-filter__list__items"
        v-for="(category, index) in categories"
        :key="index"
        @click.stop="setCurrentCategory(category)"
      >
        {{ getCollectionTotal(category) }} // Sending the category object to my method
        <a
          v-bind:class="{
            'is-selected': filters.category.includes(category.category_name)
          }"
          class="c-link c-link--filter"
          >{{ category.category_name }}
          <span>({{ category.collections_number }})</span> 
        </a>
      </li>
    </ul>
    <div id="collectionsTotal">{{ collectionsTotal }}</div> // Displaying the total here
  </div>
</template>
<script>
import state from "../store/index";
import { mapState } from "vuex";

export default {
  name: "categories-sidebar",
  computed: mapState(["filters", "categories"]),
  methods: {
    setCurrentCategory: function(category) {
      if (this.filters) {
        this.filters.category.includes(category.category_name)
          ? state.commit("delCategory", category.category_name)
          : state.commit("setCategory", category.category_name);
      }
    },
    getCollectionTotal(cat) {
      let collectionsTotal; // Warning says ‘assigned a value but never used’
      collectionsTotal += cat.collections_number;
    }
  }
};
</script>

Answer №2

In order to make your function work correctly, ensure you are returning a value and initializing your collectionsTotal variable:

calculateCollectionTotal(category) {
  let collectionsTotal = ''; // alternatively, initialize it with 0
  collectionsTotal += category.collections_number;
  return collectionsTotal;
}

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

Working with Multidimensional Arrays in VueJS

Designing a virtual toaster using VueJS, where different types of bread are toasted with varying results. The toaster should be able to toast sourdough, wheat, and rye, while rejecting white and English muffins. Additionally, rye should never burn, but t ...

Rounding up the cents area using JavaScript

So, imagine this scenario: I'm inputting a dollar amount into a text field using code similar to this: <input type="text" name="qtr-revenue-<?php echo $qtr ?>" id="qtr-revenue-<?php echo $qtr ?>" class=&quo ...

What is the best way to showcase just 5 photos while also incorporating a "load more" function with

Is there a way to display only 5 images from a list on the first load, and then show all images when the user clicks on "load more"? Here is the code I have: $('.photos-list').hide(); $('.photos-list').slice(1, 5).show(); $ ...

The jQuery hover function is not functioning properly on page load in Firefox

While this code is functioning smoothly in Chrome and IE, it seems to be encountering issues in Firefox! <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> JS: $(window).load(function(){ $("#bosti ...

Steps for generating a hierarchical menu utilizing data from a CSV file

I am looking to use a CSV file to structure the menu on my webpage. Could someone assist me in creating a nested menu using JavaScript with the provided CSV data? The columns consist of: Level, Menu name, URL 0;"Service"; 1;"Service 1";"http://some-url- ...

Verify if the scroll bar is still being held by the user

Is there a way to determine if the scrollbar is being grabbed by the user? Can the .scroll() method in jQuery be used for this purpose? $(window).scroll(function() { ... } }); I am looking to automatically scroll the div back to the top when the user ...

Guide on incorporating a library into your Ionic application without the need to upload it to npm

Recently, I successfully created an Angular application, an Ionic application, and a custom library in my workspace. I am able to import the library files into my Angular application but facing challenges when trying to import them into my Ionic applicat ...

An effective method for retrieving textarea data in Node.js

I am facing an issue where I cannot successfully send data from a <textarea> to Node.js. It seems that the data I'm trying to send is not being received by Node.js. To retrieve data in Node.js: continueBtn.addEventListener("click", ...

JSON data cannot be transmitted using AJAX

I created a function that tracks the time spent on a specific page and where the user came from. The data is collected and saved into a JSON object, but I encountered an issue when trying to send this JSON via ajax. Upon successful sending, I receive an em ...

Issue with VueJS/Nuxt: When using this.$router.push, the wrong template is being returned to the <nuxt-link> tag

Currently, I'm developing a search feature that takes the value from a select box and sends the user to the appropriate page. However, there seems to be an issue where the wrong template is being called upon rendering, resulting in no content being di ...

Arranging functions in descending and ascending order

I am working on a Table component that has an array of columns and data. I need to sort the columns and update the table state accordingly. My method takes two arguments key (column key) and sortable (true or false indicating if the column is sortable or ...

The Facebook Customer Chat Plugin embedded within an iframe

Can the Customer Chat Plugin be used within an iframe? When adding content-security-policy: frame-ancestors IFRAME_DOMAIN, it displays the message Refused to frame 'https://www.facebook.com/' because an ancestor violates the following Content Se ...

The error message "TypeError: undefined is not an object (evaluating '_reactNative.Stylesheet.create')" occurred in a React Native environment

I've been working on a project in React Native and have successfully installed all the necessary dependencies. However, upon running the code, I encounter the following error message: TypeError: undefined is not an object (evaluating '_reactNativ ...

Step-by-step guide on incorporating an external JavaScript library into an Ionic 3 TypeScript project

As part of a project, I am tasked with creating a custom thermostat app. While I initially wanted to use Ionic for this task, I encountered some difficulty in integrating the provided API into my project. The API.js file contains all the necessary function ...

Struggling to get a shader up and running on three.js using shaderfrom

Trying to add this shader to my project: This is the fragment shader code: <script id="fragmentShader" type="x-shader/x-fragment"> #ifdef GL_ES precision highp float; precision highp int; #endif uniform vec2 u_resolutio ...

The interconnected nature of multiple asynchronous tasks can lead to a render loop when relying on each other, especially when

My asynchronous function fetches data in JSON format from an API, with each subsequent call dependent on the previously returned data. However, there are instances where I receive null values when trying to access data pulled from the API due to the async ...

Another problem with CORS again?

My rails application uses the host http://myhost.dev to search for music through the vk.com API. The API provides a search method called audio.search. Below is the code snippet from my search.js.erb file which is executed via a remote link to the search ac ...

JSON.stringify does not transform arrays into strings

It seems like I may have approached this task incorrectly, perhaps due to mishandling recursion. I'm unsure of where the mistake lies. You can view the example here. Below is the JavaScript code snippet - function propertyTest(currentObject, key) { ...

Is it possible to achieve seamless image transitions in Firefox like it does in Chrome?

To achieve the desired effect, you may need to use some javascript. Visit aditagarwal.com for more information. Styling with CSS: .images-wrapper{ position: fixed; left: 0; top: 80px; bottom: 0; width: 100%; height: 100vh; an ...

Customizing order and limit features in AngularJS

I have a collection of items that I need to organize into separate lists based on priority levels. items = [ {'type': 2, 'priority': 1, 'name': 'one'}, {'type': 1, 'priority': 2, 'na ...