Home > Web Front-end > JS Tutorial > What should you pay attention to when optimizing Vue projects?

What should you pay attention to when optimizing Vue projects?

亚连
Release: 2018-06-20 15:13:58
Original
1630 people have browsed it

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

  1. 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.

  2. Don’t write too many expressions and judgments in the templatev-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.

  3. 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

  1. 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.

  2. 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.

  3. 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.

  1. 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.

  2. 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}}

  3. 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.

  4. 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.

  5. 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

  6. 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

  1. Components have clear meanings and only handle similar businesses. The higher the reusability, the better, and the stronger the configurability, the better.

  2. When encapsulating components yourself, you should still follow the rules of configuring props refinement.

  3. 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 loading

The official website link at noon is above, and the example is as follows

const Foo = r => require.ensure([], () => r(require(&#39;./Foo.vue&#39;)), &#39;group-foo&#39;) 
const Bar = r => require.ensure([], () => r(require(&#39;./Bar.vue&#39;)), &#39;group-foo&#39;) 
const Baz = r => require.ensure([], () => r(require(&#39;./Baz.vue&#39;)), &#39;group-foo&#39;)
Copy after login


This code packages the three components Foo, Bar, and Baz into a chunk file named group-foo, of course It’s a js file

Just write the rest of it normally. When the website is loaded, it will automatically analyze which chunk needs to be loaded. Although the total volume of separate packages will become larger, the speed of requesting the first screen alone is much faster. .

There are several problems and solutions faced by vuex

When the website is large enough, there are many fields in the root part of a state tree. To solve this problem, we need to modularize vuex, which is provided by the official website A modular solution allows us to configure modules when initializing vuex. Each module contains state, action, etc., which appear to be multiple state trees, but are actually subtrees based on rootState. After subdivision, the entire state structure will be clear and management will be much easier.

Due to the flexibility of vuex, coding is inconsistent. The complete closed loop is store.dispatch('action') -> action -> commit -> mutation -> getter - > computed. In fact, some of the intermediate links can be omitted, because the API document provides the following methods: mapState, mapGetters, mapActions, and mapMutations. Then any step can be directly called in the component, or you can call it however the project wants. When the project is large, we must consider the uniformity of vuex usage. My suggestion is to complete the entire closed loop no matter how simple the process is, to form a unified code and facilitate later management. Only dispatch and mapGetters are allowed to appear in my components. , the rest of the process is carried out in the vuex folder named store.

Based on the above point, let’s talk about what to do in each process. There must be inconsistencies in the front-end and back-end data, or in the data structure or field naming. So which step should handle the data conversion? What about logic? Some people will say that any step can be implemented, but this is not the case. My suggestions are as follows

  1. Before sending dispatch, process the data structure and field names of the parameters that need to be passed in the component

  2. 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

  3. 这一步是将转换后的数据更新到 state 里,可能会有数据分发的过程(传进一个 object 改变多个 state 中 key 的 value),可以转换数据结构,但是尽量不做字段转换,在上一步做

  4. 此时的 store 已经更新,使用 getter 方法来取值,token: state => state.token,单单的取值,尽量不要做数据转换,需要转换的点在于多个地方用相同的字段,但是结构不同的情况(很少出现)。

  5. 在组件里用 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>
Copy after login

在 webpack 里有个 externals,可以忽略不需要打包的库

externals: { 
 &#39;vue&#39;: &#39;Vue&#39;, 
 &#39;vue-router&#39;: &#39;VueRouter&#39;, 
 &#39;vuex&#39;: &#39;Vuex&#39;, 
 &#39;axios&#39;: &#39;axios&#39; 
}
Copy after login

此时的 vender 包会非常小,如果不够小还可以拆分其他的库,此时增加了请求的数量,但是远比加载一个 1.4M 的 bundle 快的多。

总结

本文谈的优化可以解决部分性能问题,实际开发细节很多,总之按着规范写代码,团队的编码风格尽量统一,处理细节上多加思考,大部分性能问题都能迎刃而解。

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

在Webpack中如何加载SVG

webpack打包配置(详细教程)

在Javascript中自适应处理方法

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template