vue中created得到的数据怎么在methods使用

我想在methods中使用created从缓存中得到的用户信息传递给后端,再调用getinfo得到后端返回的信息,但报错我没有理解

export default {
  name: "Person",
  data() {
    return {
      photo: "",
      nickName: "",
      id: "",
      userName:"",
      userinfo:[],
    };
  },
  created() {
    //从缓存获取登录用户信息
    let user = localStorage.getItem("user");
    if (!user) {
      console.log(history, location);
      location.href = location.origin + "#/login";
    }
    user = JSON.parse(user);
    this.$nextTick(() => {
      this.info();  // 在此处执行你要执行的函数
      });
    
    this.photo=user.photo
    this.userName =user.userName;
    this.id =user.id;
    this.$nextTick(() => {
      this.info();  // 在此处执行你要执行的函数
      });
  },
  methods: {
   
    info(user) {
        this.$http({
          url: "/admin/index",
          method: "PUT",
          data: {
          id:user.id,
          userName:user.userName
          },
        }).then((res) => {
          if(!res.errorMsg){
         this.getinfo()}
        });
      },
      getinfo(){
        this.$http({
          url: "/admin/index/userself",
        }).then((res) => {
          this.total = res.total;
          this.userinfo = res.userinfo;
        });
    
  },
  },

};

img

需要把user当作参数传到info函数里,或者在created中使用this.user = user,info函数中使用this.user获取数据

img

此处

img


应为 this.info(user);

引用chatGPT
在Vue中,created钩子是在实例创建后立即调用的,可以用来初始化数据、设置计算属性、监听事件等。如果您想在methods中使用created钩子中获取的数据,您可以将数据保存在实例的data属性中,然后在methods中使用this访问它。以下是一个示例代码:

export default {
    data() {
        return {
                myData: null
}
    },
    created() {
        // 获取数据并保存到data属性中
        this.myData = fetchData()
    },
    methods: {
        doSomething() {
            // 在methods中使用数据
            console.log(this.myData)
        }
    }
}

在这个示例中,我们在created钩子中获取数据并将其保存到实例的data属性中。然后,在methods中,我们可以使用this访问myData属性并进行处理。

img

不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 你可以参考下这个问题的回答, 看看是否对你有帮助, 链接: https://ask.csdn.net/questions/7719850
  • 除此之外, 这篇博客: 【Vue原理】Methods - 源码版中的 methods 怎么使用实例访问? 部分也许能够解决你的问题, 你可以仔细阅读以下内容或者直接跳转源博客中阅读:

    methods 简单到什么程度呢,估计你用脚都能想得到

    那么现在的问题怎么解答

    “遍历 methods 这个对象,然后逐个复制到 实例上?”

    没错,你猜对了,的确是逐个复制,简化源码是这么写的

    function initMethods(vm, methods) {    
        for (var key in methods) {
            vm[key] = 
                methods[key] == null ? 
                noop : 
                bind(methods[key], vm);
        }
    }
    



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^