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>