Skip to content

小程序中保存数据的几种方式

第一种、保存在data中,缺点是:保存、调用的时候都需要用this.data.X,不方便

第二种、保存在缓存localstorage中,缺点是:保存的数据是永久的,数据多了后页面会卡顿

第三种、保存在全局APP中,缺点是:只是单独一个页面使用的数据,保存在全局中,不好维护

上面这三种方法还有个共同的问题:

同样名称的数据只能保存一份,比如themes,数据可以替换,但不能保存多个

第四种、使用类和通过类new的对象来保存

theme.js

js
export default class Theme {

  static locationA = 't-1'

  themes = []

  async getThemes() {
    const names = `${Theme.locationA}`
    this.themes = await Http.request({
      url: `theme/by/names`,
      data: {
        names
      }
    })
  }

  getHomeLocationA() {
    return this.themes.find(t => t.name === Theme.locationA)
  }
}

home.js

js
const theme = new Theme()

await theme.getThemes()

const themeA = theme.getHomeLocationA()

备注

在theme类中定义themes,当new Theme生成对象后,调用接口请求,返回的数据保存到themes中

对外暴露数据的时候,可以封装一个方法对外暴露

备注

在实际项目开发中,要根据实际情况来选择保存数据的方法

如果要对接口返回的数据进行二次加工,我建议选择第四种方法

**随感:**使用类和类的对象来保存数据,参考的是Java中类和对象的思想,Java都是创建类,在类里定义变量和方法,使用的时候就创建类的对象,通过类的对象来调用对外暴露的方法和变量

如有转载或 CV 的请标注本站原文地址