在vue中使用类的封装可以创造出多个具有相同属性或方法的实例。实例们具有统一的属性和方法,能够保证数据的一致性。代码更加简洁,只需要将参数对象传入即可。
例如现在有如下需求(1、2):

  1. 类A,需要包含编号id,名称name,种类type,图片url。
export default class A {
	constructor(id, name, type, url){
		this.id = id
		this.name = name
		this.type = type
		this.url = url
	}
}
  1. 向A类添加一个方法,可根据id异步获取实例的其他信息getInfo()。
export default class A {
	constructor(id, name, type, url){
		this.id = id
		this.name = name
		this.type = type
		this.url = url
	}
	getInfo() {
		return axios.get(url, { id: this.id }).then((res) => {
			this.info = res.data.info
		}).catch((err) => {
			this.info = ''
		})
	}
}
  1. 当需要处理数据时,就向外部暴露一个方法createA(params)用于创建A类的实例,参数params是未整理的数据的对象。写好createA后,之后创建A的实例就通过createA函数创建。

    如果不需要处理数据,则直接使用new A(params)

export function createA(params) {
	return new A({
		id: params.id,
		name: params.name,
		type: params.type,
		url: `http://test.test.test.com/${params.id}`
	})
}
  1. 使用方法:通过_normalizeList(list)序列化整个列表。或者当功能并不复杂时,可以直接使用createA(item)创建实例。
_normalizeList (list) {
   let ret = []
   list.forEach(item => {
     if (item.id) {
       ret.push(createA(item))
     }
   })
   return ret
 }

需要获取A更多信息时,调用其getInfo()方法:

console.log(a.info) // ''
this.a.getLyric()
console.log(a.info) //data

https://github.com/Gesj-yean/vue-demo-collection 记录了更多优秀插件的使用方法。有时间的同学请看我的置顶博客,可太感谢啦。

Logo

前往低代码交流专区

更多推荐