When the page is refreshed, the route fails to load the data

My Vue.JS website is quite simple, utilizing VueX and Vue-Router.

I have defined two routes: '#/' and '#/account/' These routes are filled with components from .vue files, loaded dynamically upon page load using http-vue-loader (to avoid dealing with webpack/etc due to the small scale of the project).

The '#/' view remains static.

In the '#/account' view, the user's first and last name appear in <input type="text"> boxes.

When navigating from '#/' to '#/account', the name fields populate correctly. However, upon refreshing the browser, the textboxes empty out and only repopulate after switching to another route and returning.

The data for this component is fetched from the global VueX store, which is updated via a commit() during an AJAX call on page load.

Why do the fields not auto-populate on refresh?

Relevant code snippets:

main.js: (included as <script type="module"> in the main HTML file)

const store = new Vuex.Store({
    state: {
        user: {firstname: '', lastname: ''}
    },
    mutations: {
        updateUser(state, user){

            state.user = { ...user }
        }
    }
})


$(document).ready(function() {
let templates = {}
templates.home = httpVueLoader('./templates/home.vue')
templates.account = httpVueLoader('./templates/account.vue')
templates.not_found = httpVueLoader('./templates/404.vue')

// Define routes:
const routes = [
    { path: '/', component: templates.home },
    { path: '/account', component: templates.account },

    // Handle not found pages (place this route last):
    { path: '*', component: templates.not_found }
]

const router = new VueRouter({ routes })

// Initialize Vue app:
const app = new Vue({
    router,
    store,
    components: {

    }
}).$mount('#vueApp')

checkLogin()    // Determine if user is logged in and populate VueX store with user info.

function checkLogin() {
    // Verify user login status.
    console.log("Checking for login...")
    Get({
        url: 'https://[api-url]/v1/auth'
    })
    .then((result) => {
        console.log("Result: ", result)
        if (result.data.logged_in) {
            loadUI()
            store.commit('updateUser', result.data.user)
        }
        else
        {
            logout()
        }
    })
}

account.vue:

<template>
    ...

                    <input type="text" class="form-control" id="txtFirstname" aria-describedby="txtFirstnameHelp" v-model="firstname">
                    ...
                    <input type="text" class="form-control" id="txtLastname" aria-describedby="txtLastnameHelp" v-model="lastname">
                    ...

</template>

<script>
module.exports = {
    data: function() {
        return {

            firstname: this.$store.state.user.firstname,
            lastname: this.$store.state.user.lastname
        }
    },
    ...
</script>

<style scoped>

</style>

Answer №1

To address this issue, it is recommended to define these properties as computed properties instead of including them in the data object:

Within Account.vue:

module.exports = { data: function() { return {

    }
},
computed: {
    firstname: function() { return this.$store.state.user.firstname },
    lastname: function() { return this.$store.state.user.lastname }
},

...

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

The promise is unexpectedly fulfilled ahead of schedule without returning the expected value from an AXIOS call

My current challenge involves making a request to a service that rapidly generates multiple strings. The problem lies in returning a promise from this service, as I lack control over the string-generation process. It is crucial for me to return a promise ...

Angular page not reflecting show/hide changes from checkbox

When the user clicks on the checkbox, I need to hide certain contents. Below is the code snippet: <input id="IsBlock" class="e-field e-input" type="checkbox" name="IsBlock" style="width: 100%" #check> To hide content based on the checkbo ...

Modify the color of every element by applying a CSS class

I attempted to change the color of all elements in a certain class, but encountered an error: Unable to convert undefined or null to object This is the code I used: <div class="kolorek" onclick="changeColor('34495e');" style="background-c ...

Having trouble executing a fetch request in Next.js

I am struggling to perform a fetch request using getStaticProps in Next.js. Despite following the documentation provided on their website, I am unable to console log the props successfully. My background is mainly in React, so I tried to adapt my approac ...

JavaScript does not display checkbox values

I am currently testing whether checkbox values appear on the client side. When I execute the code, the alert is not showing anything. I would greatly appreciate any assistance, thank you. <div> <label name="finishing"class=" ...

Is there a way to store image URLs in a fashionable manner?

Hey there! I've been working on creating a HTML page that showcases multiple images. Everything is running smoothly on my localhost, but when I try to access it online, the images take forever to load. Any suggestions on how I can cache image URLs in ...

Angular-Chart.js - Issue with Tooltip not displaying for data points with a value of 0

Within my Angular Chart JS Application, I have encountered an issue where having "0" values in my data array seems to affect the functionality of the tooltip for the corresponding bar. Interestingly, changing the "0" values to "0.1" resolves the problem... ...

Steps for dynamically executing an Angular ng-include directive in real-time

Is there a way to dynamically insert an ng-include element into an HTML page and have it function properly? I am working on a Drag N Drop application where users can drag an element onto the page, and upon dropping it in the designated zone, the original ...

Personalize your BigBlueButton experience with custom HTML 5 client modifications

Does anyone know how to remove the three-dot options menu button in the Big Blue Button HTML 5 client that's installed on Ubuntu? Our setup involves displaying the html5 client inside an iframe, so we need to handle the meeting leave and end functions ...

Struggling to transfer information from JavaScript to Python Flask?

I am currently working on a basic configuration where I need to send a string to my Flask application through Ajax, but unfortunately, I am encountering Error code 400: Bad request. Here is the JavaScript code snippet: headers = { 'Content-type&a ...

Looking for subsequence in dropdown choices with no assigned values

I need assistance with searching for a specific substring within text that is fetched from options generated by MySQL. How can I retrieve the selected option's text value in order to search for my desired substring? $(document).ready(function() { ...

What is the method of posting to PHP using JavaScript without utilizing Ajax?

My current code involves a drag and drop file uploader to PHP using ajax, but it seems that my web host does not support ajax. Is there an alternative method to achieve this without using ajax? Specifically, I am facing issues with the UploadFile functio ...

Looking for solutions to manage mouseenter, mouseleave events and ensuring content dropdowns stay visible in Vue.js 2?

Hey there, I'm trying to figure out how to keep dropdown content from disappearing when using @mouseenter and @mouseleave. Here's what I have so far: <div class="wrapper"> <div class="link" @mouseenter="show = ...

Do not include iPad in the user agent redirect for iOS users

I have adapted a PHP script for detecting mobile devices into JavaScript, and it's working well. However, I want to specifically exclude tablet user agents. if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || ...

jQuery does not allow for text input values to be posted

Having an issue with a form using the POST method. I have some PHP controls that are being calculated in jQuery. While all the form control values are accessible in the next form using POST, the values added through jQuery are not posting to the next form. ...

Create an input field with a dynamic and exclusive identifier using the DataTables plugin

I am having trouble creating unique IDs for each input field based on the number of rows Here is the code snippet: $(document).ready(function() { var oTable = $('#jsontable').dataTable(); //Initialize the datatable $.ajax({ url ...

Enhance your Vue table by adding a class to the currently active row

How can I make a row in vue-good-table active so that the user can easily identify it? It seems like there isn't a feature in vue-good-table that allows us to add a class to a row. I attempted to add styling to the template slot="table-row", ...

Find out if OpenAI's chat completion feature will trigger a function call or generate a message

In my NestJS application, I have integrated a chat feature that utilizes the openai createChatCompletion API to produce responses based on user input and send them back to the client in real-time. Now, with the introduction of function calls in the openai ...

Issues with changing background colors using Jquery animate

I am attempting to create a fading background color effect when a button is clicked. Currently, I can change the background color using this code: $("#" + lblqty).css("background","#e9f1ff"); However, when I try to use the animate function as shown below ...

What are some effective techniques to optimize this node.js code and eliminate redundancy?

I am currently in the process of setting up a basic template for my demonstration project and writing my first node.js program. The piece of code below is functioning properly for my initial test, but it contains duplicated sections - Getting connection, E ...