精简 data 上数据
更新时间:
一般来讲 data 上的数据都是有响应式追踪地,首先一定要保证 data 的数据在视图中使用到了,其次要尽可能的简化 data 上面的数据。
不渲染的数据不定义在 data 上
推荐级别:强烈
不需要数据绑定或页面间传递的数据,不要定义在 data 里
反例
<template>
<text>{{a}}</text>
</template>
<script>
export default {
data: {
a: 'hello',
b: 'world',
},
onInit() {
this.a = this.a + this.b
},
}
</script>
复制代码
正例
<template>
<text>{{a}}</text>
</template>
<script>
const b = 'world'
export default {
data: {
a: 'hello',
},
onInit() {
this.a = this.a + b
},
}
</script>
复制代码
简化 data 上数据
推荐级别:建议
动态绑定的数据结构应去除冗余信息,尽可能的简单合理
反例
<template>
<list>
<list-item for="{{list}}">
<text>{{ $item.name }}</text>
<image src="{{ $item.img }}"></image>
</list-item>
</list>
</template>
<script>
export default {
data: {
list: [
{ name: 'a', value: '', img: 'image_1.png' },
{ name: 'b', value: '', img: 'image_2.png' },
{ name: 'c', value: '', img: 'image_3.png' },
{ name: 'd', value: '', img: 'image_4.png' },
],
},
}
</script>
复制代码
正例
<template>
<list>
<list-item for="{{list}}">
<text>{{ $item }}</text>
<image src="{{`image_${$idx}.png`}}"></image>
</list-item>
</list>
</template>
<script>
export default {
data: {
list: ['a', 'b', 'c', 'd'],
},
}
</script>
复制代码
不使用动态属性修改 data 上数据
推荐级别:强烈
js 的对象属性可以使用 .
和中括号两种方式去访问,尽量不要用中括号放变量去修改对象的值。这样子做会使您的数据无法被框架优化。
反例
<template>
<div>
<text>{{person.name}}</text>
<text>{{person.location}}</text>
</div>
</template>
<script>
export default {
data: {
person: {
name: 'Vance',
location: 'shenzhen',
},
},
onInit() {
const location = 'location'
this.person[location] = 'beijing'
},
}
</script>
复制代码
正例
<template>
<div>
<text>{{person.name}}</text>
<text>{{person.location}}</text>
</div>
</template>
<script>
export default {
data: {
person: {
name: 'Vance',
location: 'shenzhen',
},
},
onInit() {
this.person.location = 'beijing'
},
}
</script>
复制代码
自定义组件传参类型要简单
推荐级别:鼓励
自定义组件尽量用简单数据类型定义 props 进行传参,如 String、Number、Boolean 类型。
反例
<template>
<my-button buttonInfo="{{buttonInfo}}"></my-button>
</template>
<script>
export default {
data: {
buttonInfo: {
name: '默认值',
color: '#ff0000;',
},
},
}
</script>
复制代码
正例
<template>
<my-button name="默认值" color="#ff0000;"></my-button>
</template>
复制代码
渲染数据层级不宜过深
推荐级别:鼓励
动态绑定的数据层数不宜过深。
反例
<template>
<div>
<text>{{obj.a.name}}</text>
<text>{{obj.b.name}}</text>
</div>
</template>
<script>
export default {
data: {
obj: {
a: {
name: 'name a',
},
b: {
name: 'name b',
},
},
},
}
</script>
复制代码
正例
<template>
<div>
<text>{{obj.a}}</text>
<text>{{obj.b}}</text>
</div>
</template>
<script>
export default {
data: {
obj: {
a: 'name a',
b: 'name b',
},
},
}
</script>
复制代码