The issue of Vue js Computed property failing to update upon changing route

On my dashboard page, I encounter an issue where my computed property giveaways does not update when navigating back to the page from other links. The data retrieval works fine on page refresh but fails to update the computed property upon returning. Despite receiving the data in the response, it seems that the rendering is affected due to this issue. I am utilizing axios in vuex and have attempted using this.$forceUpdate without success. I'm unsure of the correct placement for this method call. My goal is to ensure that the computed property updates every time users visit the dashboard.vue page, whether through refreshing or vue-route navigation, so it reevaluates the data from the server side.

Below is the script for Dashboard.vue:

import {mapState} from 'vuex'
import { mapGetters } from 'vuex'

export default{
    ready(){
        this.loaded =false;

    },
    data: () => ({
        cards: [],

        loaded: true
    }),
    computed:{
        ...mapState({
            Giveaway: state => state.Threshold.giveaways
        }),

        giveaways(){
            return this.$store.getters.doneGiveaways
        },
        testing(){
            return this.$store.getters.loadTesting
        }
    },

    watch:{
        giveaways(newVal, oldVal){
            console.log(newVal + 'test');
        },
        testing(newVal, oldval){
            console.log(newVal)
        },
        deep: true
    },

    mounted(){
        this.$store.dispatch('getGiveAways');
        this.cards[2].result_val = this.$store.getters.doneGiveaways;
        if(this.$store.getters.doneGiveaways > 0){
            this.cards[2].background_color = 'orange';
            console.log('wew');
        }
        
    }
}

And here is Threshold.js Vuex:

import Vue from 'vue';
import VueAxios from 'vue-axios';
import axios from 'axios';
Vue.use(VueAxios, axios);


const state = {
    giveaways: null,
    testing: ['wew']
}

const actions = {
    getGiveAways : ({commit}) =>{
        axios({
            url : '/prod/api/thresholds_settings',
            method: 'post',
            data : {}
        })
        .then(response=>{
            if(response.status == 200){
                commit('SET_GIVEAWAYS', response.data.total_giveaways)
            }
        })
        .catch(error=>{
            if(error.response){
                console.log('something happened')
            }
        });
    }
}

const mutations = {
    SET_GIVEAWAYS : (state, obj)=>{
        state.giveaways = obj
    }

}

const getters = {
    doneGiveaways(state){
        return state.giveaways
    },
    loadTesting(state){
        return state.testing
    }
}

export default {
    state, mutations, actions, getters
}

Answer №1

Consider updating your match option with the following:

watch:{
    changes(newItem, oldItem){
        console.log(newItem + 'test');
    },
    adjustments(newVal, oldval){
        console.log(newVal)
    },
    deep: true,
    $route: this.changes
},

Alternatively, you can include the following in the router file (will need another dependency - vuex-router-store):

import { sync } from 'vuex-router-sync'
import store from './vuex/store' // vuex store instance
import router from './router' // vue-router instance

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

Ways to switch out error message for an error landing page

I am currently displaying error text when something goes wrong, but I would like to enhance the user experience by redirecting to a well-designed error page instead. Can anyone provide guidance on how to achieve this? Below is my existing code for display ...

"Error encountered: Module not found - Issue resolving module" while using signrequest-client in Angular

I've been attempting to integrate the signRequest API into my angular application. To do so, I first installed the signrequest-client using the following command: npm install signrequest-client --save Following this installation, I included the Ja ...

Is the concept of Controlled and Uncontrolled Components in VueJs similar to that of React?

When it comes to React, there is a distinction between controlled and uncontrolled components explained in detail at this link. Controlled components function within the React model where state is managed in the virtual DOM. In contrast, uncontrolled com ...

Guide on displaying the appropriate child "div" with jQuery?

I am facing a challenge with my two dependent dropdowns that toggle the visibility of divs based on user input. The first div is functioning correctly, however, every time the user makes a selection in the second div, it impacts the first div. $(docume ...

Only a singular operation is carried out

Contained within my .js file are two functions: function download510(form) { if (form.pass.value=="tokheim") { location="../pdf/quantium-510.pdf" } else { alert("Invalid Password") } }; function download410(for ...

React video recording not displaying in the video element

I'm currently developing a React application that facilitates webcam interviews with candidates. As part of this process, candidates have the option to "Start Again" or "Complete" their interviews. One challenge I am facing is displaying the recorded ...

What is the best way to display database information on my webpage according to the selected item in the combo box?

Whenever I visit my sample.php page, the only thing that appears is my combo box. However, when I start selecting a value from the combo box, that's when the data from my database, which is fetched from getyear.php, is displayed. What I want to achie ...

Encountered error message: "Cannot assign argument of type '() => () => boolean' to parameter of type 'EffectCallback'"

I recently started working with TypeScript. I encountered an issue when attempting to utilize useEffect in TypeScript within a React context, Error: Argument of type '() => () => boolean' is not assignable to parameter of type 'Effec ...

The specific error "Argument is not a function, got undefined" in the $broadcast function is exclusive to Angular on Firefox

An Angular error is popping up in Firefox but not in Chrome or IE. The specific error message is: Error: Argument 'myControllerName' is not a function, got undefined. When tracing the stack, it seems to be originating from the $broadcast function ...

What is preventing me from being able to view the contents of the hidden columns in this DataTable?

The issue at hand I am facing a challenge with accessing the content of each cell within my data table. My goal is to retrieve the text of every cell in every row, including the ones that are hidden, in order to print and display all elements accurately. ...

Using jQuery in Rails 3 to display the id of a td element

I am working with a 3x3 table that contains td elements with unique id's (id='a1'...id='c3'). I want to enable the user to click on any of these 9 td elements and receive an alert displaying the id of the clicked td. Below is my C ...

Using Blob to save CSV file on Safari

Here are the codes I am using to generate a download link for users to download a .csv file from my website. var link = document.createElement("a"); link.id = "csvDwnLink"; window.URL = window.URL || window.webkitURL; var csv = "\ufeff" + CSV, b ...

Is it possible for me to avoid html tags inside a class without using the xmp tag?

There are a few ways to approach this question. It's important to decide which method will be most beneficial for your specific needs... Is it possible for JavaScript to recreate the deprecated <xmp> tag using an "xmp" class? Can we replicate ...

Having trouble with Window.open on Mobile Devices and Canvas?

I've created a unique "button" within the div element. This button is designed to detect user interaction, such as clicks or taps, and when triggered, it should open a new window with the URL: "http://www.google.com". However, while this functionality ...

Incorporate AJAX functionality with a simple HTML button

Upon clicking the button, the AJAX call fails to execute. Below is the HTML code for the buttons: <td><button id=${data[i].id} name="update" type="button" value="${data[i].id}" class="btn btn-primary update" ...

Updating meta tags dynamically in Angular Universal with content changes

Hello, I'm encountering an issue with a dynamic blog page. I am trying to update meta tags using data fetched from the page. Here's the code snippet: getBlogPost() { this.http.get(...) .subscribe(result => { this.blogPost = re ...

excessive load on Array parameter

As a fervent Python enthusiast, I have a strong distaste for JavaScript's lack of elegance. Fortunately, I have found a solution to adapt it to my liking. import { createApp } from 'vue' import App from './App.vue' var array_len_ ...

Switch to a different form when clicked using JavaScript

Can you assist me with my code issue? The scenario is as follows: I have two forms - one for registration and one for login. I want to dynamically replace the login form with the register form when the user clicks on the "Sign up" link. Similarly, if the ...

Vuefire encountering an issue with Vue 3 and throwing a Vue.use error

After setting up a Vue app and importing Vue from the vue module, I encountered an issue: ERROR in src/main.ts:4:5 TS2339: Property 'use' does not exist on type 'typeof import("/data/data/com.termux/files/home/ishankbg.tech/node_modules/vue/ ...

Communication with parent components via event emissions in Vue is not possible

I'm working on a form with the following structure: <template> <form @submit.prevent=""> <input v-model="objective"> <div> <button @click="addTask">add</button> </div> </form& ...