The issue of data not updating in Vue.js using Vue Router 2 component

I am new to vue.js and currently working on developing a Single Page Application (SPA). Essentially, I set up all my routes from the backend with aliases to my API endpoints. Many of these routes use the same component, and data is fetched using router.beforeEach along with vue-resource.

However, I am facing an issue where when navigating from one route to another that shares the same template, my router-view does not update.

Below is a snippet of my code:


<script>

var data = {
    content: null
}

const site = {
    template:'<div>{{this.title}}</div>',
    data: function () {
      return data.content.body
    }
}

const home = {
    template:'<div>{{this.title}}</div>',
    data: function () {
      return data.content.body
    }
}

const routes = [
            { path: '/api/12.json', component: home, alias: '/' },
            { path: '/api/4.json', component: site, alias: '/projekte' },
            { path: '/api/5.json', component: site, alias: '/projekte/projekt-1' },
            { path: '/api/7.json', component: site, alias: '/projekte/projekt-2' },
            { path: '/api/6.json', component: site, alias: '/projekte/projekt-3' },
            { path: '/api/8.json', component: site, alias: '/agentur' },
            { path: '/api/9.json', component: site, alias: '/lab' },
            { path: '/api/10.json', component: site, alias: '/kontakt' },
        ]

const router = new VueRouter({
    routes
})

router.beforeEach((to, from, next) => {

    Vue.http.get(to.matched[0].path).then((response) => {

        data.content = response;
        console.log(data.content);
        next();

    }, (response) => {

        data.content = {
            'body': {
                'title': 'Error 404'
            }
        };
        next();

    });
})

const app = new Vue({
    router

}).$mount('#app')

</script>

Answer №1

The data object you are using is not integrated into your Vue component. It is actually defined outside of your Vue app.

Although the components - home and site - return the data.content.body object, the main data object is not reactive in Vue's system. As a result, any changes made to this data object will not be tracked.

To prevent this issue, it is important to define your data within the component itself. Additionally, make sure to make http calls within the mounted hook on the route component, as it has access to this.data of the component.

If there is a need to share data between components (which is common), consider utilizing state management with Vuex. This allows for a shared state across the entire Vue application.

For more information on Vuex, visit: http://vuex.vuejs.org/en/intro.html

Answer №2

Check out this example showcasing the integration of vue, vue-router, vuex, and vue-resource for making API Calls. A special thanks to Mani for providing the helpful hint.

const site = {
    template:'<div>{{ content.title }}</div>',
    computed: {
        content (){
            return store.state.routeContent
        }
    }
}

const home = {
    template:'<div>{{ content.title }}</div>',
    computed: {
        content (){
            return store.state.routeContent
        }
    }
}

const notFound = {
    template: '<div>{{ content.title }}</div>',
    computed: {
        content (){
            return store.state.routeContent
        }
    }
}

const routes = [
    { path: '/api/12.json', component: home, alias: '/' },
    { path: '/api/4.json', component: site, alias: '/projekte' },
    { path: '/api/5.json', component: site, alias: '/projekte/projekt-1' },
    { path: '/api/7.json', component: site, alias: '/projekte/projekt-2' },
    { path: '/api/6.json', component: site, alias: '/projekte/projekt-3' },
    { path: '/api/8.json', component: site, alias: '/agentur' },
    { path: '/api/9.json', component: site, alias: '/lab' },
    { path: '/api/10.json', component: site, alias: '/kontakt' },
    { path: '/*', component: notFound }
]
  
const store = new Vuex.Store({
    state: {
        routeContent: null
    },
    mutations: {
        routeContent (state, payload) {
            state.routeContent = payload
            document.title = payload.title
        }
    }
})

const router = new VueRouter({
    routes
})

router.beforeEach((to, from, next) => {

    Vue.http.get(to.matched[0].path).then((response) => {
        store.commit('routeContent', response.body)
        next()

    }, (response) => {
        console.log(response);
        errorObject = {
            'title': 'Error 404'
        },
        store.commit('routeContent', errorObject)
        next()

    });
})

const app = new Vue({
    router

}).$mount('#app')

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

Using React to dynamically set the width of a div element to match the width of an image

I am trying to ensure that my div is always the same width as the image it contains, even when the window is resized and the image adjusts automatically. I attempted to solve this using the useState hook, but it does not seem to respond to resize events. ...

Switch Between Different Background Colors for Table Rows With Each Click

This script changes colors when a row in a specific column is clicked: $(document).ready(function(){ $("#rowClick").children("tbody").children("tr").children("td").click(function(){ $(this.parentNode).toggleClass("enroute"); }); }); CSS: .placed{ b ...

Can you explain the functionality of a Radius Manager and how I can personalize it to suit my needs

Can you explain what a Radius Manager is and how I can customize it? My company wants me to create a website based on their radius manager, and they've given me three steps for the login page: 1- Verify username and password for authentication 2- Ch ...

Retrieving information from a jQuery data variable within an AJAX request in a server-side script

I have multiple ajax calls in my app that all point to the same server-side file. I am wondering if there is a way for me to use a variable to distinguish each call and select the appropriate script to send back to the client. The variable would be used on ...

What is the best way to repeatedly play an MP3 file using JavaScript and HTML?

Greetings, I appreciate you taking the time to review my website. Today, I made an attempt to add some audio to my site, but encountered an issue. My goal is for users to click a button and have an mp3 file play in a loop. While this works with wav files, ...

Troubleshooting issues with logging out in AngularJS

After attempting to logout of my current session, I realized that the logout feature is not working. Below is the code I have used: view <a ui-sref="logout"> <i class="fa fa-sign-out"></i> Log out </a> config.js $stateProvide ...

What is the best way to use the event target as the argument for $emit in VueJS2?

I am working with a VueJS 2 template var aThing = Vue.component('something',{ template :` <button @click="$emit('custom-event','hello there')">Click me</button>`}); Can the actual button that was clicked ...

Modifying HTML elements with JavaScript - a practical guide

I'm trying to dynamically add the variable x to an existing HTML tag. The goal is to update the image tag <img id="Img" src="IMG/.jpg"/> by appending the variable x at the end of its id and source: <script> var images ...

Obtaining the index of items that are returned by using the limit and sorting by descending CreateAt

My first experience with Parse has been great so far. I've successfully worked on reading and writing data. Now I am faced with a seemingly simple task, but in the Parse context, it feels like a challenge to implement and my usual search skills are n ...

Safari browser cutting off POST parameters prematurely

I am encountering an issue where my code works perfectly on all browsers except Safari 6.1.2 on Mac OS Lion. Below is the AJAX post code that I am using - $.ajax({ type: 'POST', dataType: 'text/html', url:"/MyProxy.php ...

Challenges with Vuetify forms

I have created a popup form with modularity using Vuetify. However, I encountered an issue where clicking on the email input field, deselecting it to trigger an "empty" error, and then switching over to the register tab caused a similar error for the name ...

What could be the reason for Next.js middleware rewrite not executing two times?

Issue with Next.js Middleware Execution While working on implementing next.js middleware, I encountered a situation where I needed to set up two redirects. One redirect was intended to switch a Desktop URL to a Mobile URL, and the second one aimed to modi ...

Incorporating CSS into JavaScript/Ajax functionality

mypage() is a lengthy function that provides information such as page numbers, total number of pages, and the next page in a pagination system. selectPage() is a JavaScript/Ajax script used to send the current page number to the server. While my CSS file ...

Adding Rotation to a group in Three.js using a pivot point

I'm currently in the process of constructing a Rubik's Cube using Three.js. My method involves grouping all the small cubes that need to be rotated together and then performing the rotation on the group as a whole. To determine the pivot point fo ...

Modify the array value and access it outside of an asynchronous function

Is there a way to set values in an array from an asynchronous function and access it outside of that function's scope? I am working on a project where I need to randomize values in an array, so that I can assign images randomly to different div eleme ...

Harness the power of external JavaScript to initiate a click event within a Next.js component

Recently, I've been given the task of manually updating a UI that was developed using Next.js. One particular element in the UI is repeated countless times (okay, not exactly a million but you get it), and my job is to toggle its state by clicking on ...

Tips for effectively implementing correct reselection in a React-Redux application

I have a system that allows users to search for data based on their input. I am currently implementing reselect in my application. import React, { useEffect } from "react"; import { useDispatch, useSelector } from "react-redux" ...

What could be causing the mousewheel event in my code to remain active?

Whenever I try to scroll on Google Chrome, an error occurs on my website. jquery-3.3.1.min.js:2 [Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See To resolve this issue: $(document).ready(f ...

`How can I troubleshoot path obstacles when transferring files in node.js?`

I am having trouble moving a file from an HTML form to another folder using a cloud function. I am new to both node.js and firebase, so I am unsure of what I am doing wrong. This is my current code snippet: const fileMiddleware = require('express-mult ...

Issues involving the handleChange function in React can be a frustrating and common hurdle

I am encountering an issue with the handleChange function in my React project. Upon loading data from JSONPlaceholder and clicking on the 'Edit' button, a form is displayed with the selected user's information. However, when trying to edit ...