Skip to content

类和类的对象在前端项目中的使用

以小程序项目为例,谈一下如何在项目中使用类和类的对象

问题

在小程序项目,如何保存数据?

现在有themes数据要进行保存

js
const themes = theme.getTheme()

解决办法

第一种、保存在data中

js
this.data.themes = themes

缺点:调用麻烦,获取和赋值都需要用this.data;js里代码混乱

第二种、放到localstorage中

缺点是:保存的数据是永久的,维护麻烦

第三种、放到全局App中

缺点是:themes数据只在首页中使用,保存在全局中维护麻烦而且没有必要

备注

上面三种方法有个共同的问题:themes数据只能保存一份,不能保存不同的themes数据

第四种、类和类的对象(推荐)

类和通过new 类生成的对象,这是面向对象的思想

class类可以用来保存数据

类的对象可以用来保存数据和状态

举个例子:

js
const t1 = new Theme()
t1.a = 1

const t2 = new Theme()
t2.a = 2

同一个类生成的不同对象,可以保存不同数据的相同值

在项目中可以这样写

新建theme.js文件

js
import {Http} from "../utils/http";

class Theme {
    static locationA = 't-1'
    static locationE = 't-2'

    themes = []

    static forYou = 't-6'

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

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

    getHomeLocationE() {
        return this.themes.find(t => t.name === Theme.locationE)
    }

}

在home.js里使用

js
initAllData() {
  const theme = new Theme()
  await theme.getThemes()

  const themeA = theme.getHomeLocationA()
  const themeE = theme.getHomeLocationE()
}

总结

当做前端项目的时候,如果要对接口返回的数据进行二次加工:

1、新建一个类,在这个类里定义变量,接收接口返回的数据并将其赋值给这个变量,

js
themes = []

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

2、类中新建方法,方法里对数据进行处理并返回

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

getHomeLocationE() {
  return this.themes.find(t => t.name === Theme.locationE)
}

3、使用的地方引入这个类并生成对象,通过对象调用方法,获取加工后的数据

js
initAllData() {
  const theme = new Theme()
  await theme.getThemes()

  const themeA = theme.getHomeLocationA()
  const themeE = theme.getHomeLocationE()
}

备注

类中的变量和方法不用加static,因为这是要被生成的对象调用的

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