简体   繁体   中英

Vue3 LocalStorage set after component render

I have a nav bar that loads user data, all of this happens after a user successfully logs into the application. The problem is, localStorage must be setting slightly after I load the nav bar. If I wrap it in a setTimeout() everything works but I would rather my variables be reactive in nature since they can change based on user activity.

Toolbar.vue

<template>
  <!--begin::Toolbar wrapper-->
  <div class="d-flex align-items-stretch flex-shrink-0">
    <h2>check for value</h2>
    <div v-if="activeAccountId">{{activeAccountId}}</div>
  </div>
  <!--end::Toolbar wrapper-->
</template>

<script lang="ts">
import { defineComponent, ref } from "vue";

export default defineComponent({
  name: "topbar",
  data() {
    let activeAccountId = ref(JSON.parse(localStorage.getItem('activeAccountId') || '{}')).value;

    return {
      activeAccountId
    }
  }
});
</script>

I've tried using watchers, and using setup() verses data(), but nothing seems to work properly. As I mentioned, setTimeout() does work but I'd rather avoid manually triggering a timeout and let vue handle things how it wants to.

Here's a simple example, I can't setup a dummy code side since it won't have the localStorage item set.

For some additional context, after the user is logged in, I am hitting the API with an async() to get the account information and storing the account data in localStorage. I'm guessing at the same time the router is trying to load the navbar area which is why the localStorage items aren't available when the component mounts.

I don't know the vue3 words to use, but ideally I would want some type of async/await call to localStorage because the ref() doesns't seem to be working how I thought it would. It's as if the ref() doesn't see localStorage get updated.

localStorage being synchronous is the main issue.

use mounted lifecycle hook. and initialize user information there

Vue calls the mounted() hook when the component is added to the DOM. You can try putting your initial code in the mounted method and also try to change your code like this

 export default defineComponent({ name: "topbar", data() { return { activeAccountId:"" } }, mounted(){ this.activeAccountId = JSON.parse(localStorage.getItem('activeAccountId')|| '{}'); } });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM