最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Avoid that when refreshing the page, the global status is lost with Vuex and VueRouter - Stack Overflow

programmeradmin1浏览0评论

I'm creating a SPA, and as a basic example of sessions on the client side, I'm using Vuex to store a boolean state if the user is logged in or not, it works fine while not manually updating the browser. As the state restarts to its initial state, is there any way to prevent this or should it always use localstorage? If so, how to get the initial state of storage?

Component Navbar

<template>
    <div>
        <ul v-if="!isLogued">
            <router-link :to="{ name:'login'}" class="nav-link">Login</router-link>
        </ul>
        <ul  v-if="isLogued">
                <a href="#" class="nav-link">Profile</a>
                <a href="" @click.prevent="logout">Salir</a>
        </ul>
    </div>
</template>
<script>
    import {mapState,mapMutations  } from 'vuex';
    export default{
        puted : mapState(['isLogued']),
        methods:{
            ...mapMutations(['logout']),
        }
    }
</script>

Store.js

export default {
    state: {
        userLogued: {},
        api_token  : '',
        isLogued : false
    },
    mutations: {

        login( state){
            state.userLogued = JSON.parse(localStorage.getItem('usuario'));
            state.api_token = localStorage.getItem('api_token');
            state.isLogued =  true
        },

        logout(state){
            state.userLogued = {}
            state.isLogued = false
            state.api_token  = null
            localStorage.clear()
        }
    }
};

App.JS

Vue.use(VueRouter)
Vue.use(Vuex)

import store from './vuex/store';
import routes from './routes';
const router = new VueRouter({
    mode: 'history',
    routes
})

const app = new Vue({
   router,
   store : new Vuex.Store(store)
}).$mount('#app')

In my login ponent, I do post with axios and if it is correct I do the following

   methods : {
        ...mapMutations(['login']),
        sendLogin(){
            axios.post('/api/login' , this.form)
                .then(res =>{
                    localStorage.setItem('api_token', res.data.api_token);
                    localStorage.setItem('user_logued', JSON.stringify(res.data.usuario));
                    this.login();
                    this.$router.push('/');
                })

I'm creating a SPA, and as a basic example of sessions on the client side, I'm using Vuex to store a boolean state if the user is logged in or not, it works fine while not manually updating the browser. As the state restarts to its initial state, is there any way to prevent this or should it always use localstorage? If so, how to get the initial state of storage?

Component Navbar

<template>
    <div>
        <ul v-if="!isLogued">
            <router-link :to="{ name:'login'}" class="nav-link">Login</router-link>
        </ul>
        <ul  v-if="isLogued">
                <a href="#" class="nav-link">Profile</a>
                <a href="" @click.prevent="logout">Salir</a>
        </ul>
    </div>
</template>
<script>
    import {mapState,mapMutations  } from 'vuex';
    export default{
        puted : mapState(['isLogued']),
        methods:{
            ...mapMutations(['logout']),
        }
    }
</script>

Store.js

export default {
    state: {
        userLogued: {},
        api_token  : '',
        isLogued : false
    },
    mutations: {

        login( state){
            state.userLogued = JSON.parse(localStorage.getItem('usuario'));
            state.api_token = localStorage.getItem('api_token');
            state.isLogued =  true
        },

        logout(state){
            state.userLogued = {}
            state.isLogued = false
            state.api_token  = null
            localStorage.clear()
        }
    }
};

App.JS

Vue.use(VueRouter)
Vue.use(Vuex)

import store from './vuex/store';
import routes from './routes';
const router = new VueRouter({
    mode: 'history',
    routes
})

const app = new Vue({
   router,
   store : new Vuex.Store(store)
}).$mount('#app')

In my login ponent, I do post with axios and if it is correct I do the following

   methods : {
        ...mapMutations(['login']),
        sendLogin(){
            axios.post('/api/login' , this.form)
                .then(res =>{
                    localStorage.setItem('api_token', res.data.api_token);
                    localStorage.setItem('user_logued', JSON.stringify(res.data.usuario));
                    this.login();
                    this.$router.push('/');
                })
Share asked Apr 8, 2018 at 5:06 DarkFenixDarkFenix 7461 gold badge13 silver badges39 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

You will need to always be using a persistent storage mechanism if you want to preserve state across page reloads, browser sessions, etc. You can use localStorage, sessionStorage, cookies, indexeddb... whichever best suits your needs, although sessionStorage is of course only good for the current session.

To restore the initial state, use a plugin for Vuex, such as vuex-peristedstate. This will take case of the saving/restoring vuex to storage for you.

For example, creating an instance of vuex-persistedstate for use in your store is as easy as:

import createPersistedState from 'vuex-persistedstate'

const store = new Vuex.Store({
  // ...
  plugins: [createPersistedState()]
})

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>