In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Today, I will talk to you about Vue optimization skills, which may not be well understood by many people. In order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.
Using key in Code Optimization v-for
When v-for is used to update the rendered element list, the local reuse strategy is used by default. When the list data is modified, he will judge whether a certain value is modified according to the key value. If so, re-render this item, otherwise reuse the previous element.
Considerations for using key:
Do not use key values that may repeat or change (the console will also give you a reminder)
Do not use the index of the array as the key value, because if you insert an element in the array, the element index that follows it will change.
If there is no unique key value available in the array, consider adding a key field to it, with a value of Symbol () to ensure uniqueness.
Using key in v-if/v-else-if/v-else
Maybe many people will ignore this point.
Why: by default, Vue updates DOM as efficiently as possible. This means that when it switches between elements of the same type, it patches an existing element instead of removing the old one and adding a new one in the same place. If elements that are different are identified as the same, unexpected side effects can occur.
If there is only one v-if and no v-else or v-if-else, there is no need to add key
Compared with the key of v-for, key in v-if/v-else-if/v-else is relatively simple. We can write a fixed string or array directly.
Save Edit .v-enter-active, .v-leave-active {transition: all 1s;} .v-enter, .v-leave-to {opacity: 0; transform: translateY (30px);} .v-leave-active {position: absolute;}
For example, for the above code, you will find that although you have added a transition effect to button, you cannot trigger the transition without adding a key switch
Do not use v-for and v-if together (Vue2)
This optimization technique is limited to adjusting the priority of v-for and v-if in Vue2,Vue3.
Everyone knows that.
Never use v-if and v-for on the same element at the same time. Lead to Vue2.x style Guide
The reason is that v-for takes precedence over v-if, so when they are used on the same label, each rendering loops before judging the condition.
Note: v-if takes precedence over v-for in Vue3, so when v-for and v-if are used together, the effect is similar to that of v-if uplink in Vue2.
For example, the following code is not recommended in Vue2, and Vue will give a corresponding warning.
{{user.name}}
We should try to move the v-if to the superior or use computational properties to process the data.
{{user.name}}
If you don't want to add an unnecessary parent container to the contents of the loop, you can choose to use template as its parent element. Template will not be rendered as a DOM node by the browser.
If I want to judge the contents of each item in the traversal object to select the rendered data, I can use computed to filter the traversal object
/ / jslet usersActive = computed (() = > users.filter (user = > user.active)) / / template {{user.name}} reasonable selection of v-if and v-show
The difference between v-if and v-show is familiar to everyone; v-if controls the display and hiding of elements by directly manipulating the deletion and addition of DOM; v-show controls the display and hiding of elements by controlling DOM's display CSS familiarity.
Because the performance of the add / remove operation on DOM is much lower than the CSS attribute of the operation DOM
So when elements need to show / hide changes frequently, we use v-show to improve performance.
When the element does not need to show / hide changes frequently, removing the DOM through v-if can save some of the resources needed by the browser to render this DOM.
Use simple calculation properties
Complex computational attributes should be split into as many simpler property as possible.
Easy to test
When each evaluated property contains a very simple and rarely dependent expression, it is easier to write tests to ensure that they work correctly.
Easy to read
Simplified calculation properties require you to give each value a descriptive name, even if it is not reusable. This makes it easier for other developers (and you in the future) to focus on the code they care about and figure out what's going on.
Better "embrace change"
Any value that can be named can be used on the view. For example, we may intend to display a message telling users how much they have saved, or we may plan to calculate taxes, but we may show them separately rather than as part of the total price.
Small, focused computing properties reduce hypothetical restrictions on the use of information, so there is no need for so much refactoring when requirements change.
Lead to Vue2 style Guide
Computed is familiar to you later, and it is recalculated when the responsive data that its expression depends on changes is sent. If we write a more complex expression in an evaluation attribute, the responsive data it depends on becomes more and more at will. When any of these dependencies change, the entire expression needs to be recalculated
Let price = computed (() = > {let basePrice = manufactureCost / (1-profitMargin) return (basePrice-basePrice * (discountPercent | | 0))})
When any one of manufactureCost, profitMargin, or discountPercent changes, the entire price is recalculated.
But if we change it like this,
Let basePrice = computed (() = > manufactureCost / (1-profitMargin)) let discount = computed (() = > basePrice * (discountPercent | | 0)) let finalPrice = computed (() = > basePrice-discount)
If only discount and finalPrice are recalculated when discountPercent changes, basePrice will not be recalculated because of the cache nature of computed
Functional functional components (Vue2)
Note that this is only used as an optimization tool in Vue2; in 3.x, the performance difference between stateful and functional components has been greatly reduced and is negligible in most use cases. Therefore, the migration path for developers using functional on SFCs is to delete the attribute and rename all references to props to $props and attrs to $attrs.
Before optimization
Export default {props: ['value'],}
After optimization
Export default {props: ['value'],}
No this (no instance)
No responsive data
Split component
What? A vue file you wrote has more than a thousand lines of code? ?
A reasonable split of components can not only optimize performance, but also make the code clearer and readable. The principle of single function
Derived from https://slides.com/akryum/vueconfus-2019#/4/0/3
Before optimization
{{heavy ()}} export default {props: ['number'], methods: {heavy () {/ * HEAVY TASK * /}
After optimization
Export default {props: ['number'], components: {ChildComp: {methods: {heavy () {/ * HEAVY TASK * /}}, render (h) {return h (' div', this.heavy ()}
Because the update of Vue is component-grained, although each frame is re-rendered by the parent component through data modification, ChildComp does not re-render because there are no responsive data changes within it. So the optimized component does not perform time-consuming tasks every time it is rendered.
Use local variables
Before optimization
{{result}} import {heavy} from'@ / utils'export default {props: ['start'], computed: {base () {return 42}, result () {let result = this.start for (let I = 0; I)
< 1000; i++) { result += heavy(this.base) } return result } }} 优化后 {{ result }}import { heavy } from '@/utils'export default { props: ['start'], computed: { base () { return 42 }, result () { const base = this.base let result = this.start for (let i = 0; i < 1000; i++) { result += heavy(base) } return result } }} 这里主要是优化前后的组件的计算属性 result 的实现差异,优化前的组件多次在计算过程中访问 this.base,而优化后的组件会在计算前先用局部变量 base,缓存 this.base,后面直接访问 base。 那么为啥这个差异会造成性能上的差异呢,原因是你每次访问 this.base 的时候,由于 this.base 是一个响应式对象,所以会触发它的 getter,进而会执行依赖收集相关逻辑代码。类似的逻辑执行多了,像示例这样,几百次循环更新几百个组件,每个组件触发 computed 重新计算,然后又多次执行依赖收集相关逻辑,性能自然就下降了。 从需求上来说,this.base 执行一次依赖收集就够了,把它的 getter 求值结果返回给局部变量 base,后续再次访问 base 的时候就不会触发 getter,也不会走依赖收集的逻辑了,性能自然就得到了提升。 引至 揭秘 Vue.js 九个性能优化技巧 使用 KeepAlive 在一些渲染成本比较高的组件需要被经常切换时,可以使用 keep-alive 来缓存这个组件 而在使用 keep-alive 后,被 keep-alive 包裹的组件在经过第一次渲染后,的 vnode 以及 DOM 都会被缓存起来,然后再下一次再次渲染该组件的时候,直接从缓存中拿到对应的 vnode 和 DOM,然后渲染,并不需要再走一次组件初始化,render 和 patch 等一系列流程,减少了 script 的执行时间,性能更好。 注意: 滥用 keep-alive 只会让你的应用变得更加卡顿,因为他会长期占用较大的内存 事件的销毁 当一个组件被销毁时,我们应该清除组件中添加的 全局事件 和 定时器 等来防止内存泄漏 Vue3 的 HOOK 可以让我们将事件的声明和销毁写在一起,更加可读 function scrollFun(){ /* ... */}document.addEventListener("scroll", scrollFun)onBeforeUnmount(()=>{document.removeEventListener ("scroll", scrollFun)})
Vue2 can still do this with $once, and of course you can destroy events in optionsAPI beforeDestroy, but I recommend the former because the latter makes the code with the same function more decentralized
Function scrollFun () {/ *... * /} document.addEventListener ("scroll", scrollFun) this.$once ('hook:beforeDestroy', () = > {document.removeEventListener ("scroll", scrollFun)}) function scrollFun () {/ *... * /} export default {created () {document.addEventListener ("scroll", scrollFun)}, beforeDestroy () {document.removeEventListener ("scroll", scrollFun)}} picture load
Picture lazy loading: suitable for situations where there are more pictures on the page and not all pictures are displayed in one screen. The vue-lazyload plug-in provides us with a very convenient picture lazy loading instruction v-lazy.
However, not all images are suitable for lazy loading. For example, banner and photo albums are more recommended to use image preloading technology, which gives priority to downloading the previous and latter images currently displayed.
Adopt reasonable data processing algorithm
This relatively tests the skills of data structures and algorithms.
For example, a method of converting an array into a multi-level structure
/ * Array transtree structure, time complexity O (n) * @ param list array * @ param idKey element id key * @ param parIdKey element parent id key * @ param parId parent id value * @ return {[]} * / function listToTree (list,idKey,parIdKey,parId) {let map = {}; let result = []; let len = list.length / / build map for (let item0; I < len; item0 +) {/ / convert the data in the array to a key-value pair structure (where the array and obj will refer to each other, which is the focus of the algorithm) map [I] [idKey]] = list [I];} / build a tree array for (let item0; I < len; item0 +) {let itemParId = list [I] [parIdKey] / / Top-level node if (itemParId = parId) {result.push (list [I]); continue;} / / Orphan node, discarded (no parent) if (! map [itemParId]) {continue } / / insert the current node into the children of the parent node (because it is a reference data type, if the node in obj changes, the corresponding node in result will change) if (map [itemParId] .children) {map [itemParId] .children.push (list [I]);} else {map [itemParId] .children = [list [I] }} return result;} other
In addition to the above methods, there are a lot of optimization techniques, but I am not very common in the project?
Freeze objects (prevent data that does not need to be responsive to become responsive)
Long list rendering-batch rendering
Long list rendering-dynamic rendering (vue-virtual-scroller)
...
First screen / volume optimization
I mainly have the following optimization directions about the first screen optimization in the project.
Volume
Code segmentation
The network
Volume optimization
Compressed packaging code: webpack and vite production environment packaging will compress your code by default. This generally does not require special processing, and webpack can also be implemented manually through the corresponding compression plug-in.
Cancel source-map: you can check whether there is a .map file in your package, and if so, you can turn off code mapping by setting the value of source-map to false or empty (this takes up a really large volume).
Packaging to enable gizp compression: this requires the server to enable gizp transmission, otherwise it will not be useful to enable it (webpack has a corresponding gzip compression plug-in, a different version of the webpack compression plug-in may be different, it is recommended to query the official website first)
Code segmentation
The role of code segmentation is to divide the packaged product into a small product, which depends on esModule. So when you use the import () function to import a file or dependency, the file or dependency is packaged separately as a small artifact. Both routing lazy loading and asynchronous components use this principle.
Routing lazy loading
Asynchronous component
I generally don't use on-demand loading components for UI libraries, but prefer to optimize them in a way that CDN introduces.
The network
CDN: first of all, the CDN mentioned above is introduced, and the development phase uses native libraries to eliminate these dependencies when packaging by configuring external extensions (Externals). Then introduce them in the html file by means of CDN
Server Push: HTTP2 is relatively mature; with the introduction of CDN above, we can use HTTP2's Server Push function on the website to get browsers to load these CDN and other files ahead of time.
Enable gzip: as mentioned above, the principle is that when both the client and the server support gzip transmission, the server will first send the files compressed by gzip, and then the client will receive the decompression.
Turn on caching: generally, I use negotiation caching, but this does not apply to all cases. For example, for files that use Server Push, you can't change their names at will. So I usually fix the file name of the main file in production.
After reading the above, do you have any further understanding of Vue optimization techniques? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.