What should you pay attention to when optimizing Vue projects?
This article mainly introduces the method of optimizing the Vue project. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let’s follow the editor and take a look.
It’s been a long time since I wrote a blog post. This article is a summary of my experience in using the vue framework for half a year. Let’s talk about it casually. This article is only applicable to projects initialized by vue-cli or relying on webpack. Packaged items.
A few days ago, I saw everyone saying that the larger the Vue project, the more difficult it is to optimize, which brings a lot of pain. This is unavoidable. The problem must be solved eventually. There is no problem with the performance of the framework. All major testing websites have it. related data. Let’s get to the point
Basic optimization
The so-called basic optimization is required for any web project and is the root of the problem. HTML, CSS, and JS are the first steps to optimize.
corresponds to ,<template>,<style>,<script>,
in the .vue file respectively. Let’s talk about the points worth optimizing in the vue project one by one
template
Semantic tags, avoiding random nesting, reasonably naming attributes and other standard recommended things Let’s not talk about it.
The template part helps us display structured data. Vue drives the view through data. Pay attention to the following points
Which one should be used for v-show and v-if? In my opinion, we need to think about the problem in two dimensions. The first dimension is the permission issue. As long as it involves permission-related display, v-if will undoubtedly be used. The second dimension is selected based on the frequency of user clicks without permission restrictions. , use v-show for frequent switching, and use v-if for infrequent switching. The optimization point to be mentioned here is to reduce the total number of DOM in the page. I prefer to use v-if, because it reduces the number of DOM and speeds up the first screen rendering. , As for performance, I feel that the switching rendering process cannot be seen with the naked eye, and it will not affect the user experience.
Don’t write too many expressions and judgments in the template
v-if="isShow && isAdmin && (a || b)",
This kind of expression Although the expression can be identified, it is not a long-term solution. When it looks uncomfortable, write it appropriately in methods and computed and encapsulate it into a method. The advantage of this is that it is convenient for us to judge the same expression in multiple places, and other permissions are the same. Just call the same method when the element is judged for display.Add a key when calling subcomponents in a loop. The key can uniquely identify a loop individual. For example, item.id can be used as the key. If the array data is like this
['a' , 'b', 'c', 'a'],
Use:key="item"
Obviously it doesn't make sense, a better way is to use(item, index) when looping ) in arr, then:key="index"
to ensure the uniqueness of the key.
style
Should the style file be placed inside or outside the vue file? It is meaningless to discuss. The focus is on dividing by modules. My habit is to put it inside the vue file. It is convenient to write code by jumping up and down in the same file. Regardless of internal or external suggestions, add
<style scoped>
Lock the style file. The purpose is very simple. No matter how easy-to-use the standard is, it cannot avoid the trouble of multi-person development. The agreed naming rules may also conflict. After locking the area, try to use short naming rules. No need for.header -title__text
and other classes can be done directly with .title.In order to distinguish it from the previous one, let’s talk about the global style file. The global style file should be as abstract as possible. Since it is not repeated in every component, it should be as general as possible. This part The better the abstraction, the smaller the size of your style file and the higher the reuse rate. It is recommended to put the code of the copied component library such as Element style into the global.
Do not use float layout. I have seen many people encapsulate
.fl -- float: left
Go to the global file, and then .clear, now The browser is not so weak that you have to use float for compatibility. It is fully compatible with flex, and the grid compatibility is average. In fact, the function can be implemented in flex layout. Float will bring layout troubles. Anyone who has used it knows that they don’t believe in the explanation pit. .
As for other general specifications, I won’t go into details here. There are many related articles.
script
This part is also the most difficult to optimize. Let me give you my personal opinion.
When developing with multiple people, try to keep the order of methods in each component consistent
export default {}
to facilitate finding the corresponding method. I personally use data, props, hooks, watch, computed and components.data What I want to say is that the structure of the initialized data should be as detailed as possible, with clear naming, simple and easy to understand, and avoid useless variables. isEditing can actually represent two states, true or false, no Then define notEditing to control the display, which can be done in the template
{{ isEditing ? Editing: Save}}
props When passing values to parent and child components, try to:width="" :heigth="" Do not:option={}. The advantage of refinement is that only the parameters that need to be modified are passed and added in the child component props. The data type, whether it must be passed, and the default value make it easier to troubleshoot errors and make the value transfer more rigorous.
The hook just needs to understand the meaning of the life cycle, when should the request be made, when should the method be logged out, and which methods need to be logged out. Simple and easy to understand, it is written on the official website.
-
Every method in methods must be simple and only do one thing. Try to encapsulate short and reusable methods without too many parameters. If you rely heavily on lodash for development, method will look much simpler, but the cost is that the overall bundle size will be larger. If the project only uses a small number of methods, loadsh can be introduced locally. If you don't want to use lodash, you can encapsulate a util.js file yourself
Which question to use between watch and computed can be found on the official website for examples. Calculated attributes are mainly a layer of filter conversion. Do not add some calling methods. The function of watch is to monitor data changes to change data or trigger Events such as
this.$store.dispatch('update', { ... })
Component optimization
## The componentization of #vue is loved by everyone. The extent to which components are reasonable depends on the size of the project. Small projects can be completed with just a few components, without even using vuex, axios, etc. If the scale is large, it must be detailed. Divide components into components, the more detailed the better, including layout encapsulation, buttons, forms, prompt boxes, carousels, etc. It is recommended to look at the code of the Element component library. If you don’t have time to write in such detail, you can directly use the Element library and optimize it in several points- Components have clear meanings and only handle similar businesses. The higher the reusability, the better, and the stronger the configurability, the better.
- When encapsulating components yourself, you should still follow the rules of configuring props refinement.
- Component classification, I habitually divide it into three categories, page, page-item and layout. Page is the routing control part, and page-item belongs to each layout block in the page such as banner. , side, etc., place components that appear at least twice on multiple pages in the layout, such as icon, scrollTop, etc.
vue-router and vuex optimization
In addition to switching routes, vue-router uses the most logic for processing permissions. I won’t go into details about permission control here. There are many related demos and articles. When it comes to optimization, it is worth mentioning that component lazy loadingThe official website link at noon is above, and the example is as followsconst Foo = r => require.ensure([], () => r(require('./Foo.vue')), 'group-foo') const Bar = r => require.ensure([], () => r(require('./Bar.vue')), 'group-foo') const Baz = r => require.ensure([], () => r(require('./Baz.vue')), 'group-foo')
This code packages the three components Foo, Bar, and Baz into a chunk file named group-foo, of course It’s a js file
- Before sending dispatch, process the data structure and field names of the parameters that need to be passed in the component
- When it comes to action, we are allowed to do a lot of things, because this module supports asynchronous, state, rootState, commit, dispatch, getters. This shows that the responsibility is heavy. First, if the backend requires some other modules The data inside must be integrated into the original data through the rootState value. The next step is to issue a request and suggestion (async await axios). After getting the data, perform filtering and conversion, and then send commit to mutation
这一步是将转换后的数据更新到 state 里,可能会有数据分发的过程(传进一个 object 改变多个 state 中 key 的 value),可以转换数据结构,但是尽量不做字段转换,在上一步做
此时的 store 已经更新,使用 getter 方法来取值,token: state => state.token,单单的取值,尽量不要做数据转换,需要转换的点在于多个地方用相同的字段,但是结构不同的情况(很少出现)。
在组件里用 mapGetters 拿到对应的 getter 值。
打包优化
上面说了代码方面的规范和优化,下面说下重点的打包优化,前段时间打包的 vender bundle 足足 1.4M,app bundle 也有 270K,app bundle 可以通过组件懒加载解决,vender 包该怎么解决?
有人会质疑是不是没压缩或依赖包没去重,其实都做了就是看到的 1.4M。
解决方法很简单,打包 vender 时不打包 vue、vuex、vue-router、axios 等,换用国内的 bootcdn 直接引入到根目录的 index.html 中。
例如:
<script src="//cdn.bootcss.com/vue/2.2.5/vue.min.js"></script> <script src="//cdn.bootcss.com/vue-router/2.3.0/vue-router.min.js"></script> <script src="//cdn.bootcss.com/vuex/2.2.1/vuex.min.js"></script> <script src="//cdn.bootcss.com/axios/0.15.3/axios.min.js"></script>
在 webpack 里有个 externals,可以忽略不需要打包的库
externals: { 'vue': 'Vue', 'vue-router': 'VueRouter', 'vuex': 'Vuex', 'axios': 'axios' }
此时的 vender 包会非常小,如果不够小还可以拆分其他的库,此时增加了请求的数量,但是远比加载一个 1.4M 的 bundle 快的多。
总结
本文谈的优化可以解决部分性能问题,实际开发细节很多,总之按着规范写代码,团队的编码风格尽量统一,处理细节上多加思考,大部分性能问题都能迎刃而解。
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
The above is the detailed content of What should you pay attention to when optimizing Vue projects?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

There are three ways to refer to JS files in Vue.js: directly specify the path using the <script> tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses <router-link to="/" component window.history.back(), and the method selection depends on the scene.

Implement marquee/text scrolling effects in Vue, using CSS animations or third-party libraries. This article introduces how to use CSS animation: create scroll text and wrap text with <div>. Define CSS animations and set overflow: hidden, width, and animation. Define keyframes, set transform: translateX() at the beginning and end of the animation. Adjust animation properties such as duration, scroll speed, and direction.

Function interception in Vue is a technique used to limit the number of times a function is called within a specified time period and prevent performance problems. The implementation method is: import the lodash library: import { debounce } from 'lodash'; Use the debounce function to create an intercept function: const debouncedFunction = debounce(() => { / Logical / }, 500); Call the intercept function, and the control function is called at most once in 500 milliseconds.

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.
