Table of content
- Use
key
- Feeze object
- Use composition function (Vue2)
- Use computed
- lazy v-model
- v-model
- 保持对象引用稳定
- Use v-show instead of v-if
- defer
- keep-alive
- 长列表优化
- 打包体积优化
Use key
Normally use key
when you have v-for
, and this key
should be unique and stable, won't change over time.
It's not good to use index as key.
Freeze object
For some case, we don't need to convert all the object to reactive. Depends on use case, we can choose to freeze some objects, so that Vue won't convert it to reactive.
When we check an object is frozen or not, better to use Object.isExtensible()
, due to a frozen object is not extensible and object by default is extensible.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/isExtensible
// New objects are extensible.
const empty = {};
Object.isExtensible(empty); // true// They can be made un-extensible
Object.preventExtensions(empty);
Object.isExtensible(empty); // false// Sealed objects are by definition non-extensible.
const sealed = Object.seal({});
Object.isExtensible(sealed); // false// Frozen objects are also by definition non-extensible.
const frozen = Object.freeze({});
Object.isExtensible(frozen); // false
Use composition function (Vue2)
The anchored heading component we created earlier is relatively simple. It doesn’t manage any state, watch any state passed to it, and it has no lifecycle methods. Really, it’s only a function with some props.
https://v2.vuejs.org/v2/guide/render-function#Functional-Components
Use computed
It has cache to improve the performacne.
lazy v-model
When use v-model
to bind a form field, user change the field statau / value, the data will also change; then Vue will rerender; which cause some performance problem.
We can use lazy
or not to use v-model
to resolve the problem. But need to be careful the data and UI might out of sync for a small time period.
v-model.lazy
listen for @change
event. v-model
listen for @input
event.
When data change by using v-model
, the CSSDOM and DOM tree will be rerender, when you have animation running and change the form field at the same time, you will feel animation become slow.
保持对象引用稳定
For primive value, we need to make sure the value doesn't change.
For object, need to keep reference doesn't change.
As long as data doesn't change then Vue won't rerender the view.
handleAdd1
evertime calling the function will change the comments1
object, so that the component will be rerender everytime
handleAdd2
doesn't change the comments2
reference, so that each comment
object keep the same, only newly added component will be render.
v-if vs v-show
v-show doesn't delete/add DOM everytime.
defer
Check out https://www.cnblogs.com/Answer1215/p/18573369