刷新页面时,路由未填充数据

时间:2020-01-20 03:35:49

标签: javascript vue.js vuex vue-router

我有一个使用Vue.JS,VueX和Vue-Router的非常基本的网站。

我定义了两个路由:“#/”和“#/ account /” 这些路由由.vue文件中的两个组件填充,并通过http-vue-loader在页面加载时动态加载(以避免由于项目太小而处理webpack / etc)。

“#/”视图是静态组件。

“#/帐户”视图在<input type="text">框中显示用户的名字和姓氏。

如果我从“#/”导航到“#/帐户”页面,则正确填充了名字/姓氏。但是,如果我随后刷新浏览器,则这些文本框将变为空白,并且直到我导航到另一条路线并再次返回后才重新填充。

此组件中的数据是从全局VueX存储中加载的,由于AJAX调用,页面存储在commit()上被加载。

为什么页面刷新后不会填充这些字段?

相关代码:

main.js :(从主html文件作为<script type="module">加载)

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')

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

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

const router = new VueRouter({ routes })

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

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

checkLogin()    // Check if user is logged in - if so, populate VueX store with user info.

function checkLogin() {
    // Check if user is already logged on.
    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>

1 个答案:

答案 0 :(得分:1)

解决方法是将这些属性声明为计算属性,而不是在data对象中返回它们:

在Account.vue中:

module.exports = { 数据:function(){ 返回{

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

...