Vue中mounted钩子函数不能获取到data中的数据解决方法

1.为什么在mounted()获取不到data中的数据?

这是因为在mounted()钩子函数中,this 指向的是window作用域,所以会出现获取到的data中的数据出现没有定义的情况。

2.解决办法:

解决办法很简单,只需要解决 this 的指向问题,便可以重新获取到data中的数据,如将 this 指定另一个变量,这样在mounted() 钩子函数的子函数中,便可以重新获取到data中的数据。以下是我自己程序的部分代码:

mounted() {
    var that=this;
    // 组件通信,动态改变头像
    this.bus.$on("toChangePhoto", function() {
      document.getElementById("p").src = localStorage.getItem("photo");
    });
    // 重新设置导航栏上的用户名
    this.bus.$on("toChangeName", function() {
      that.user.name = localStorage.getItem("name");
    });
  },

大家只需要注意 this 的指定问题即可。

发布了125 篇原创文章 · 获赞 68 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/qq_42109746/article/details/101982318