Props
props定义应尽量详细。
showLoading: {
type: Boolean,
default: () => true,
required: true,
validator: () =>{
return []
}
}
避免v-for
和v-if
用在一起
当 Vue 处理指令时,v-for 比 v-if 具有更高的优先级,所以这个该模板会做map操作,每次改变都必须重新遍历整个列表。
建议:先自己做过滤操作,筛选出需要渲染的数组,再做v-for绑定。
<li v-for="(user, index) in activeUsers" :key="index">{{ user.name }}</li>
computed: {
activeUsers() {
this.users.filter((user)=> {
return user.active
})
}
}
推荐使用自闭合组件
自闭合组件表示它们不仅没有内容,而且刻意没有内容。其不同之处就好像书上的一页白纸对比贴有“本页有意留白”标签的白纸。而且没有了额外的闭合标签,你的代码也更简洁。
<my-component />
组件有多个属性、事件时应推荐换行
多个特性的元素应该分多行撰写,每个特性一行。
<el-table border
max-height="500"
ref="table"
:data="tableData"
:height="height"
:stripe="stripe"
:size="size"
:fit="fit"
:show-header="showHeader"
:highlight-current-row="highlightCurrentRow"
:current-row-key="currentRowKey"
:row-class-name="rowClassName"
:row-style="rowStyle"
:cell-class-name="cellClassName"
:cell-style="cellStyle"
:header-row-class-name="headerRowClassName"
:header-row-style="headerRowStyle"
:header-cell-class-name="headerCellClassName"
:header-cell-style="headerCellStyle"
:row-key="rowKey"
:empty-text="emptyText"
:default-expand-all="defaultExpandAll"
:expand-row-keys="expandRowKeys"
:default-sort="defaultSort"
:tooltip-effect="tooltipEffect"
:show-summary="showSummary"
:sum-text="sumText"
:summary-method="summaryMethod"
:span-method="spanMethod"
:select-on-indeterminate="selectOnIndeterminate"
@select="onSelect"
@select-all="onSelectAll"
@selection-change="onSelectionChange"
@cell-mouse-enter="onCellMouseEnter"
@cell-mouse-leave="onCellMouseLeave"
@cell-click="onCellClick"
@cell-dblclick="onCellDblclick"
@row-click="onRowClick"
@row-contextmenu="onRowContextmenu"
@row-dblclick="onRowDblclick"
@header-click="onHeaderClick"
@header-contextmenu="onHeaderContextmenu"
@sort-change="onSortChange"
@filter-change="onFilterChange"
@current-change="onCurrentRowChange"
@header-dragend="onHeaderDragend"
@expand-change="onExpandChange" />
在v-for
设置键值key
在组件上总是必须用 key
配合 v-for
,以便维护内部组件及其子树的状态。甚至在元素上维护可预测的行为,比如动画中的对象固化(object constancy),也是一种好的做法。
在 v-if
/v-if-else
/v-else
中使用 key
如果一组 v-if + v-else 的元素类型相同,最好使用 key (比如两个 <div> 元素)。
默认情况下,Vue 会尽可能高效的更新 DOM。这意味着其在相同类型的元素之间切换时,会修补已存在的元素,而不是将旧的元素移除然后在同一位置添加一个新元素。如果本不相同的元素被识别为相同,则会出现意料之外的副作用。
尽量不要在scoped
中使用元素选择器
在 scoped 样式中,类选择器比元素选择器更好,因为大量使用元素选择器是很慢的。
为了给样式设置作用域,Vue 会为元素添加一个独一无二的特性,例如 data-v-f3f3eg9
。然后修改选择器,使得在匹配选择器的元素中,只有带这个特性才会真正生效 (比如 button[data-v-f3f3eg9]
)。
问题在于大量的元素和特性组合的选择器 (比如 button[data-v-f3f3eg9]
) 会比类和特性组合的选择器 慢,所以应该尽可能选用类选择器。