简体   繁体   English

如何更改 vue-component 中的数据

[英]How to change data in vue-component

In Vue component I have some data that comes from a localStorage.在 Vue 组件中,我有一些来自 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?也许还有其他方法可以检查组件中本地存储中的 output 数据? 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.看起来问题可能与您的user变量不是一段反应性有状态数据的方式有关。 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.您的问题中没有足够的代码让我们确定这一点,但看起来您已经接近掌握在 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.我将user保存在data区域中,以便模板在值更改时对其做出反应。

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. loadUser方法是分开的,因此可以从不同的地方调用它,比如从用户登录事件中调用,但是我确保从组件的created事件中调用它。

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.实际上,我倾向于将user放入 Vuex 存储和操作中的loadUser方法,以便它可以更全局可用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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