The default data value in the Vue component is taking precedence over the value I specified in beforeRouteUpdate

When navigating in my Vue application, I utilize vue-router's beforeRouteEnter and beforeRouteUpdate to retrieve data from a REST API.

<template>
  <div>
    <h2>{{ league.name }} </h2>
    <user-list :users="league.leaderboard" type="list"/>
  </div>
</template>

<script>
import UserList from '../components/UserList.vue'
import League from '../model/League'
export default {

    components: {
        UserList
    },

    data() {
        return {
            league: { name: 'init', leaderboard: [] },
        }
    },

    methods: {
        setLeague(league) {
            this.league = league
        }
    },

    beforeRouteEnter(to, from, next) {
        League.$find(to.params.league)
            .then(league => {
                next(vm => {
                    vm.league = league
                })
            })
            .catch(err => {
                if(err.response && err.response.status == 404)
                    next('/404')
                else
                    next(vm => vm.error = err)
            })
    },

    watch: {
        league() {
            console.log('league changed ', this.league)
        }
    },

    beforeRouteUpdate(to, from, next) {
        this.league = null
        League.$find(to.params.league)
            .then(league => {
                this.setLeague(league)
                console.log('beforeUpdate: ', this.league)
                next()
            })
            .catch(err => {
                if(err.response && err.response.status == 404)
                    next('/404')
                else {
                    this.error = err
                    next()
                }
            })
    }
}
</script>

<style>

</style>

the beforeRouteEnter guard works as expected.

In my application, there's a situation where the route changes from /leagues/1 to /leagues/1, causing the component to be reused and triggering the beforeRouteUpdate guard. Despite successfully fetching new data, when calling next(), the `this.league` data reverts back to the initial value (name: 'init' etc.) defined in the data function. The reason behind this behavior remains unclear.

This code was adapted following the vue docs instructions here.

An interesting observation is that setting `this.league = null` triggers the watcher, while `this.setLeague` does not. Additionally, the output logged in beforeUpdateRoute is not a vue observer but the plain league object itself. Attempts to modify the `this.setLeague` call did not resolve the issue.

Answer №1

Encountering a similar issue, I decided to tackle it by creating a new Test component for testing purposes. During my investigation, I noticed that the `created()`, `mounted()`, and `data()` hooks were firing twice, indicating that the router was recreating the component instead of caching it. Upon further examination of the App component, I discovered the root cause of this behavior. By assigning a unique key to each route, I ensured that different instances of the component were used for distinct paths (e.g., `/test/page/1` and `/test/page/2`). Removing the key resolved the issue and restored normal functionality.

If you encounter the same code snippet in your main Component, consider replacing it with the updated version provided below.

<template>
  <router-view :key="$route.fullPath"></router-view>
</template>

<template>
  <router-view></router-view>
</template>

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

What is the process for converting error messages in veevalidate into a different language?

I am facing an issue with validating forms in real-time using Vue and VeeValidate within Laravel. The error messages are displaying in English on the veevalidate page, but I find the example provided to be unclear. Can anyone offer guidance or assistance? ...

Tips for effectively incorporating global CSS into a Nuxt3 and Vite project?

I am facing a challenge with integrating global sass into my project efficiently. There appear to be two popular methods for adding CSS in a project. vite: { plugins: [svgLoader()], css: { preprocessorOptions: { scss: { ...

Material-UI Masonry: Eliminate excess spacing on the right side

When utilizing Material-UI, I encountered an issue where the width of the Masonry Component does not completely fill the width of its parent container. The empty space left has a width exactly equal to the spacing between elements, which is understandable ...

Updating the parent component does not automatically update the props in the child component

Within my parent component, I have established the state that is then passed down as props to the child component. Additionally, I am passing the "onUpdateQuestion" function in the child component's props. This function triggers a re-render each time ...

Inject an HTML or jade webpage into a div within another HTML or jade webpage

I'm facing an issue in my Node.js project with a script (JS) that is responsible for loading a Jade page into a div of another Jade page using $("#div").load(directory). Despite specifying the directory of the jade page to be loaded, I keep getting an ...

Saving functions in the localStorage API of HTML5: A step-by-step guide

I have encountered an issue while trying to store an array in local storage using JSON.stringify. The array contains functions (referred to as promises) within an object, but it seems that when I convert the array to a string, the functions are removed. Su ...

Are arrays being used in function parameters?

Can the following be achieved (or something similar): function a(foo, bar[x]){ //perform operations here } Appreciate it in advance. ...

What is the process for sending an HTTP request within the Dialogflow -> Fulfillment environment?

When it comes to interacting with the API of my website to rectify the response for Google Assistant, I am facing some difficulties. 'use strict'; var requestNode = require('request'); const functions = require('firebase-function ...

Is it possible to interact with a particular point or element within a canvas using languages like javascript, jquery, or selenium?

I am trying to figure out how to simulate a click at a specific position within a canvas. I have tried using coordinates, but so far haven't found a way to make it work. Any other suggestions would be greatly appreciated. It's important to note t ...

In order to use the serve command, it is necessary to run it within an Angular project. However, if a project definition cannot be located

An error occurred while running the ng serve command: C:\Mysystem\Programs\myfwms>ng serve The serve command needs to be executed within an Angular project, but a project definition could not be found. I encounter this error when ...

Updating content with Ajax in Laravel

Hey, I'm currently facing an issue with my update functionality. Below is the blade code snippet: <div class="form-group floating-label" id="role_colaboration1"> <select name="{{$role}}[]" id="role" class="form-control"> ...

Implement a CSS style for all upcoming elements

I'm currently developing a Chrome extension tailored for my personal needs. I am looking to implement a CSS rule that will be applied to all elements within a certain class, even if they are dynamically generated after the execution of my extension&ap ...

The Vue component is not displaying any data

Although Axios is successfully loading data, it's not displaying anything. Laravel Mix is also building without any errors. The code I have is as follows: index.html (body) <div id="app"> <posts></posts> </div> In app.j ...

No longer will popups be blocked

I've been trying to work with jQuery to create a popup. But I'm facing an issue where my code is being blocked by Google. Here is the code snippet: <script type="text/javascript"> $(document).ready(function () { var flag = true; ...

Having trouble with CSS and javascript files not resolving after moving app to a new Windows 7 development machine

I have recently migrated my ASP.Net 3.5 web site from my old XP sp3 machine to a new Win 7 64-bit dev machine. The web application utilizes Master Pages, App_Themes with style sheets and images, as well as an image folder located off the main root. Additio ...

Counting the visible elements in Slick carousel

I have implemented slick.js to display a grid of 6 items (2 rows, 3 columns) per slide. I am looking for a way to include both the standard prev and next arrow navigation as well as an indication of the active item count for pagination assistance. For exa ...

Is it possible to configure route localization in Next.js and next-i18next to function as an URL alias?

Currently, I am utilizing NextJs version 10.0.5 in conjunction with next-i18next version 8.1.0 to localize my application. With the introduction of subpath routing for internationalized routing in NextJs 10, I encountered a situation where I needed to modi ...

Encountering issues with loading styles in Vue single file components

While working on my project at this link, I encountered an issue with displaying a styled modal. Despite trying to import the styles using: <style scoped> @import "../styles/modal-style.css"; </style> and even directly pasting the co ...

The code seems to be malfunctioning in a separate JS file, but oddly enough, it functions properly when placed within a <script> tag

I am trying to create a loader, but I have encountered an issue where the script works when placed directly in the HTML file, but not when it is in a separate JavaScript file. Here is the script: var loader = document.getElementById("ld"); w ...

Combining Two Validation Methods for jQuery Validate Plugin

Seeking advice on how to incorporate custom validation methods from jQuery validate into another method for validating data. Specifically, I have a 'Document ID' field that can accept either CPF or CNPJ (Brazilian documents) and I need to validat ...