Article Directory
-
- 1 Use of v-if and v-show
- 2 differentiated use of computed and watch
- 3 v-for traversal must add key to item, and avoid using v-if at the same time
- 4 Pure display long list performance optimization
- 5 Destruction of the event
- 6 Lazy loading of image resources
- 7 routing lazy loading
- 8 Third-party plug-ins are introduced on demand
- 9 Optimize the performance of unlimited lists
- 10 Server-side rendering SSR or pre-rendering
As we all know, the Vue project uses two-way data binding and virtual DOM. It is very efficient to replace DOM with data-driven frequent rendering. It has been very optimized for developers, so why is there still Vue performance optimization? ?
Because Vue 2.x currently uses third-party packaging and building tools such as webpack, and supports other third-party plug-ins, when we use these tools in the project, different operations may have different effects on running or packaging efficiency. The following is To elaborate on the direction of optimization.
1 Use of v-if and v-show
v-if
Itfalse
will not be renderedDOM
to the view when it is not ,true
and it will be rendered to the view when it is not;v-show
No matter what the initial condition is, the element will always be rendered to the view, and it is simply switched based on the CSS display property.
Best practice: Frequently switch to show hidden elements
v-show
, and rarely change the usev-if
2 differentiated use of computed and watch
computed
: Attribute is calculated, rely on other attribute values, and thecomputed
values are缓存
only dependent on its attribute value changes, the next acquisitioncomputed
recalculated only when the value of thecomputed
value;watch
: It is more of the function of "observation", similar to the monitoring callback of some data, each time the monitored data changes, the callback will be executed for subsequent operations;
Best practice: When we need to perform numerical calculations and rely on other data, we should use computed, because we can use the cache feature of computed to avoid recalculation every time we get a value; when we need to execute when the data changes For asynchronous or expensive operations, watch should be used. Using the watch option allows us to perform asynchronous operations (access to an API), limit the frequency with which we perform the operation, and set the intermediate state before we get the final result. These are things that calculated properties cannot do.
3 v-for traversal must add key to item, and avoid using v-if at the same time
Now, without adding the key
error that would normally be reported, adding it key
can facilitate the Vue internal mechanism to accurately find the list data. When updating, the new state value is compared with the old state value, and the diff is located faster
v-for
Than v-if
high priority, if every time need to traverse the entire array, it will affect the speed, especially when the need to render a small part of the time, if necessary, should be replaced with a computed
property.
<ul>
<li v-for="user in adminUsers" :key="user.id">
{
{ user.name }}
</li>
</ul>
<script>
export default {
data () {
return {
users: [] }
},
computed: {
adminUsers: function(){
return this.users.filter(()=>user.isAdmin)
}
}
}
</script>
4 Pure display long list performance optimization
For data that is only used for display, there is no need to do vue data hijacking, just freeze this object:
export default {
data () {
return {
users: []
}
},
created () {
axios.get('/api/users').then((res)=>{
this.users = Object.freeze(res.data.users)
})
}
}
5 Destruction of the event
When a Vue component is destroyed, it will automatically clean up its connection with other instances, unbind all its instructions and event listeners, but only for the events of the component itself. If within js use addEventListene
other means will not self-destruct, we need to listen to manually remove these events when the component is destroyed, so as not to cause memory leaks, such as:
created() {
addEventListener('click', this.click, false)
},
beforeDestroy() {
removeEventListener('click', this.click, false)
}
6 Lazy loading of image resources
Use vue-lazyload
plug-ins:
install
npm install vue-lazyload --save-dev
man.js reference
import VueLazyload from 'vue-lazyload'
Vue.use(VueLazyload)
// 或自定义
Vue.use(VueLazyload, {
preLoad: 1.3,
error: 'dist/error.png',
loading: 'dist/loading.gif',
attempt: 1
})
Modify the img tag
<img v-lazy="/static/img/1.png">
7 routing lazy loading
Vue is a single-page application, and there may be many routes introduced. In this way, the files packaged with webpcak are very large. When entering the homepage, too many resources are loaded, and the page will appear blank, which is not conducive to the user experience. If we can divide the components corresponding to different routes into different code blocks, and then load the corresponding components when the routes are accessed, it will be more efficient. This will greatly increase the speed of the first screen display, but the speed of other pages may be reduced.
const Foo = () => import('./Foo.vue')
const router = new VueRouter({
routes: [
{
path: '/foo', component: Foo }
]
})
8 Third-party plug-ins are introduced on demand
When we use third-party libraries, it is best to introduce global demand rather than the introduction, because more plug-in third-party libraries are all incorporated will be packaged slower, as Element UI
, Ant Design of Vue
and other UI library:
On-demand introduction
import Vue from 'vue';
import {
DatePicker } from 'ant-design-vue';
Vue.use(DatePicker);
Global introduction
import Antd from 'ant-design-vue';
Vue.use(Antd);
9 Optimize the performance of unlimited lists
If you are rendering with infinite scrolling list is loaded, then the need to use 窗口化
technology to optimize performance, only a small part of the region need to render content, reducing re-rendering components and create a dom node time. You can refer to the following open source projects vue-virtual-scroll-list and vue-virtual-scroller to optimize this infinite list scene.
We all went to Github
see the instructions for use of it.
10 Server-side rendering SSR or pre-rendering
Generally, single-page applications complete page rendering on the browser side, and the data is obtained from the background by sending a request; while the server-side rendering SSR is the structure of page elements (HTML) that has been built on the server side, and the entire The page is returned to the client.
What are the advantages and disadvantages of SSR:
- Better
SEO
: Web crawlers can directly crawl the page information to be included in search engines, while the content of ajax asynchronous requests will not be included, so the complete page information rendered through SSR is more conducive to SEO; - Support hook function only supports
beforCreate
andcreated
the server needs to be in Node Server environment; - Need higher server configuration: because it includes data processing and page rendering, server expenses become larger
If the loading speed of the first screen is relatively high or SEO is required, SSR rendering can be used.
PS: Optimization is just a suggestion. You need to consider whether it is suitable for your project, including optimization difficulty, scope of influence, applicable scenarios, whether it affects other modules, whether the optimization effect is obvious, and so on. What suits you is the best!