Calculating the length of an array in Vue/Nuxt using a custom plugin: Watch vs Computed

I am trying to show the length of an array within my Vue component. The array is nested within a Vue plugin.
Each time I initiate an API Call, I add a new element to this array located here: this.$apiCall.apiCallCache

Is it possible to monitor changes in this array? Am I making a mistake in the example provided below?

I am consistently seeing 0. However, if I click the button and trigger logApiCache(), it correctly logs the array's length, while the computed function still displays 0 in the span element / tooltip.

<template>
    <v-footer
        app
        tile
    >
        <span>Queue: {{ footerClockTooltip() }}</span>
        <app-footer-button
            :name="'Clock'"
            :tooltip="footerClockTooltip()"
            :icon="$icons.mdiClockOutline"
            @click="logApiCache"
        />
    </v-footer>
</template>

<script>
export default {
    name: 'Footer',
    computed: {
        /*
        footerClockTooltip() {
            return this.$apiCall.apiCallCache.length
        }
        */
    },
    methods: {
        logApiCache() {
            this.$forceUpdate()
            console.error(`logApiCache: ${this.$apiCall.apiCallCache.length}`, this.$apiCall.apiCallCache)
        },
        footerClockTooltip() {
            console.error('New Queue:', this.$apiCall.apiCallCache.length)
            return this.$apiCall.apiCallCache.length
        }
    }
}
</script>

Edit:

Here is my Vue plugin:

import Vue from 'vue'
const ApiClass = require('../classes/ApiClass')
const api = new ApiClass()

// Export Vue Plugin
const ApiCalls = {
    install(Vue) {
        Object.defineProperties(Vue.prototype, {
            $apiCall: {
                get() {
                    return api
                }
            }
        })
    }
}

Vue.use(ApiCalls)

Thank you for your assistance. :)

Answer №1

After dedicating a substantial amount of time to researching, I finally stumbled upon a solution that worked for me.
The first step I took was introducing a new property to my footer component, setting it to a default value of apicalls: null. Following this, I implemented a created() section in my component, connecting the local property apicalls to this.$apiCall.apiCallCache to achieve reactivity. With this in place, my computed function began to function correctly.

Subsequently, I discovered an even more straightforward solution. By slightly altering how I assigned my vue plugin with Vue.observable(api):

import Vue from 'vue'
const ApiClass = require('../classes/ApiClass')
const api = new ApiClass()

// Export Vue Plugin
const ApiCalls = {
    install(Vue) {
        Vue.prototype.$apiCall = Vue.observable(api)
    }
}

Vue.use(ApiCalls)

I am puzzled as to why this new method rendered my array reactive, while my initial approach did not. Any insights on this matter would be greatly appreciated.

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

Exploring the time complexity of Vue v-if and v-if-else conditions

I am currently working on a Vue project and I have a question regarding the time complexity of Vue's v-if, v-else-if statements. Is it O(n) or O(1)? In my project, I am using a component in Vue that acts like a switch case, handling different cases a ...

Improving the visualization of large GPS tracks on Google Earth Plugin

I need to display GPS routes on Google Earth using the Google Earth API. However, with approximately 20,000 points per route, the performance is not optimal. The code I have implemented successfully draws the tracks but struggles with rendering time and tr ...

Tips for customizing the selection tip of a custom cursor using CSS

I have integrated a color picker jquery plugin on my website to allow users to pick colors from an image. I made a modification in the CSS to change the cursor to an eyedropper icon. However, currently when clicking on the image, the color pointed by the u ...

Issue with Material UI dropdown not selecting value on Enter key press

I have encountered an issue with the material UI dropdown component that I am using. When I navigate through the dropdown options using arrow keys and press enter, the selected value does not get highlighted. Below is the code snippet for the dropdown: ...

Exploring Vue CLI: Guidelines for updating, deleting, and browsing through all available plugins

After diving into the world of Vue.js, I quickly realized that Vue CLI is essential for speedy development. I got it up and running, created an app, and everything seems to be going smoothly. I decided to enhance my project by adding the Vuetify.js plugin ...

What are the steps to ensure my MERN application refreshes properly when deployed on Heroku?

After successfully deploying my MERN app to Heroku, I encountered an issue where pages would come up blank when refreshed. Despite being able to navigate between pages using the nav bar without any errors, a page refresh renders them empty. This troublin ...

Chat system utilizing Laravel websockets

Hey there, I've been working on setting up a real-time chat feature using Laravel. I managed to configure the websockets and establish a connection successfully. However, I've encountered an issue when trying to send a message. I followed a tutor ...

Executing a jQuery function only once per click on a select element - how can it be done?

I have a form with a select element, and I want some code to run when I click on it, but not when I choose an option. The issue is that the code is running twice, preventing me from selecting an option as it resets itself each time. Here is the HTML: &l ...

Docker: CORS policy is blocking access to XMLHttpRequest

After creating an ASP.NET Web Application (.NET Framework) project in Visual Studio 2022 and adding a web service to it, everything seemed to work fine when testing the web service call on Local IIS. However, things took a different turn when I tried runni ...

Keep moving the box back and forth by pressing the left and right buttons continuously

Looking to continuously move the .popup class left and right by clicking buttons for left and right movement. Here is the js fiddle link for reference. This is the HTML code structure: <button class="right">Right</button> <button class="l ...

display the $scope as undefined in an angular application

Below is my code snippet: var exchange = angular.module('app', []); exchange.controller('ExchangeController', ExchangeController); function ExchangeController($scope, $http) { $scope.items = []; $http ...

Navigating the rollout of a fresh new design

When implementing a new design on a website, how can you bypass the need for users to clear their browser cache in order to see the updated changes? Is there a way to automatically refresh the cache once a new version of the website is uploaded, or are th ...

Manipulate Input Classes by Adding and Removing Them

I am currently using masked JS in some input fields, specifically for telephone numbers. However, I am facing an issue where phone numbers can vary in length, either 10 or 11 digits. I need to switch the class based on whether a checkbox is checked. Here i ...

Using Vue's $emit method within a Promise

I am currently working on an image upload feature that is based on a Promise. Within the "then" callback, I am attempting to $emit an event named 'success'. Although my VueDevTools shows me that the success event has been triggered, the associate ...

Using the symbol for pi in a JavaScript program rather than its numerical value, while still performing calculations with the numerical value behind the scenes

I am working on a calculator project where I want the symbol for pi to be displayed instead of the numerical value. Here is the relevant function: function Pi(pi) { document.getElementById('resultArea').innerHTML += pi; eval(document.ge ...

What is the best way to assign dynamic values for array destruction?

Is there a way for me to avoid manually writing out six lines by implementing a loop to retrieve all six values from one line instead? console.log(array[0].name.LINE1) console.log(array[0].name.LINE2) console.log(array[0].name.LINE3) console.log(array[1].n ...

The 'with()' function in Eloquent is returning a null value

I am currently facing an issue with a simple relationship setup between two models: User and Prescription. A user can have multiple prescriptions associated with them. However, in the PrescriptionsController, when I attempt to retrieve the user that the pr ...

Angular 2 TypeScript: Accelerating the Increment Number Speed

I'm working with a function in Angular 4 that is triggered when the arrow down key is pressed. Each time the arrow down key is hit, the counter increments by 1. In this function, I need to run another function if the counter reaches a certain speed. ...

Encountered an error while attempting to execute the command npx create react app: spawn UNKNOWN error occurred

After attempting to execute a basic npx create-react-app, an unexpected error occurred: D:\>npx create-react-app abc npx: installed 67 in 4.255s Creating a new React app in D:\abc. Installing packages. This might take a couple of minutes. In ...

Difficulty persisting data changes in Vue.js list

Trying to reorganize a list of data has been quite the challenge. Despite assigning each li a unique key, I've had no success! I had this working flawlessly before, exactly as shown below. I feel like I'm losing my mind! let app = new Vue({ ...