使用Vue.prototype存储数据

395 阅读1分钟

场景

第一次进入公众号首页需要调接口查询数据,然后将数据存起来,每次切换到首页不要重复去调接口查数据。等关闭页面下一次进入首页再重新查询。

代码

main.js

Vue.prototype.userInfo = Vue.prototype.userInfo || {}

QueryIndex.vue

mounted(){
  let home = this.userInfo.home //主页的信息
  if(home && home.point && home.callBalance){
      this.point = home.point
      this.callBalance = home.callBalance
      return;
  }
  //没有数据就去调接口
  this.userInfo.home = {)
  this.queryPoint()
  this.queryCall()
}

methods:{
	queryPoint(){
    	......//调接口获取数据
        this.userInfo.home = { //将数据存起来
          ...this.userInfo.home,
          point: res.data.body//接口返回的数据
        }
    }
}