简体   繁体   中英

How to change data in vue-component

In Vue component I have some data that comes from a localStorage.

if (localStorage.getItem("user") !== null) {
  const obj_user = localStorage.getItem('user');
  var user = JSON.parse(obj_user);
} else {
  user = null;
}
return {
  user
}

After in this component I have to check this data. I do it like this

  <li v-if="!user"><a href="/login">Login</a></li>
  <li v-if="user">
    <a href="#"><span>{{user.name}}</span></a>
  </li>

But the data does not change immediately, but only after the page is reloaded. Right after I login in on the page and redirected the user to another page, I still see the Login link. What am I doing wrong? Maybe there is some other way how to check and output data from the localstorage in component? Thank you in advance.

It looks like the issue may be related to they way that your user variable is not a piece of reactive stateful data. There isn't quite enough code in your question for us to determine that for sure, but it looks like you are close to grasping the right way to do it in Vue.

I think my solution would be something like this...

export default {
  data() {
    return {
      user: null,
    }
  },
  methods: {
    loadUser() {
      let user = null;
      if (localStorage.getItem("user")) {
        const obj_user = localStorage.getItem("user");
        user = JSON.parse(obj_user);
      }
      this.user = user;
    }
  },
  created() {
    this.loadUser();
  }
}

I save the user in the data area so that the template will react to it when the value changes.

The loadUser method is separated so that it can be called from different places, like from a user login event, however I'm making sure to call it from the component's created event.

In reality, I would tend to put the user into a Vuex store and the loadUser method in an action so that it could be more globally available.

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