Home > Web Front-end > JS Tutorial > body text

Example sharing Vue Family Bucket practical project summary

小云云
Release: 2017-12-28 09:44:50
Original
2628 people have browsed it

From a front-end perspective, Vue can be said to be the most ideal front-end MVVM framework at present. Everything serves the interface, and it is easy to get started. This article will record the reconstruction of a Vue family bucket (Vue+Vue-router+Vuex). The process of the jQuery+template project and what I learned during the process. This article mainly introduces the Vue Family Bucket practical project summary (recommended). The editor thinks it is quite good, so I will share it with you now and give it as a reference. Let’s follow the editor to take a look, I hope it can help everyone.

Getting Started

Vue’s official document is the best tutorial for learning Vue. There is no one. Maybe because the framework author is a designer and has no back-end background, so each All kinds of abstract concepts can be explained in the most understandable way in Vue. Here we only briefly introduce the concepts of Vue, Vue-router, and Vuex. For a comprehensive study, it is recommended to go to the official documentation.

Vue

The core function of Vue is two-way binding, which can automatically realize interface-driven data changes and data-driven interface changes, which can greatly reduce the cost of front-end rich interactive applications. development costs. There is more than one similar framework like Vue, but the implementation of Vue has certain advantages in performance by leveraging the native features of ES5.

Vue-router

Vue-router is the official route, used to organize the mapping relationship between urls and components, and automatically respond to url changes to the components. , so that developers only need to focus on component development, and routing will help you solve related trivial problems.

Vuex

Vuex provides a centralized data management model to deal with complex data flow situations, such as multiple components sharing data but working independently. It may cause that the synchronized data is not synchronized, or because the hook of the Object object in js points to the same instance in the memory, once the original data is manipulated, it will contaminate other components. In this case, a more organized data operation mode is needed. That's Vuex.

Technical Selection

Comparison with jQuery

After understanding the basic concepts of Vue, you will definitely be unconscious. Comparing them with the jQuery technology stack to see if these things are really necessary for my business.

First of all, can the problems solved by MVVM be solved with jQuery? The answer is yes. Do you remember using jQuery to get values ​​from inputs one by one when submitting the form? This is interface-driven data; if you have done any asynchronous interactive functions, you should have experience using jQuery to fill Ajax data into various elements in the interface. This is a data-driven interface. Although it can be done, it is a bit cumbersome. Even if you use a form verification plug-in and a front-end template engine, you still need to manually call the verification method and rendering method on each running node. It is okay to make a website page, but when the requirements are complex to a certain extent, This will be a big burden.

Then there is routing. The essence of routing is to achieve interface switching and interface maintenance by operating URLs. It is necessary for single-page applications. This actually has nothing to do with the technology stack. As long as routing requirements are generated, even projects based on jQuery can It's just a re-created route, but single-page applications are rarely made in the jQuery era.

Vuex is completely based on the extension of two-way binding, which is equivalent to adding a broker between the data and the component. The component cannot directly operate the data, and can only submit operation requirements to the broker, and the broker To implement operations to solve various unpredictable problems caused by too many people and many hands, the data was moved out of the application and a store was specially established to eliminate the problem of data contamination between components. It should be said that jQuery does not have this demand, because jQuery completely operates data manually, and there are no unexpected situations at all.

Applicable scenarios

After comparing with jQuery, the applicable scenarios of Vue are obvious. From a development perspective, projects with more complex interactions are more suitable. Single pages Most suitable, content-based websites are least suitable. If there are needs for individual pages in the website, it can also be used locally, such as shopping cart pages.

Of course, all this must be based on the premise that it is not compatible with IE8. I am a little confused about this because I saw that some 2C sites are using Vue. How did these front-end ers fool their bosses? ?

Project Analysis

Project Background

The refactoring project is the front-end component management developed for the previous company System, I chose to reconstruct this project because I am familiar with the requirements. This is a typical single-page application with moderate complexity, so it is more suitable for a hands-on exercise.

The background of the project is that in outsourcing website building companies, a large number of reusable components are accumulated in the design process. Designers often only need to fine-tune the components to piece together the page and deliver it to the front end. In theory, these components can also be reused on the front end. Used, but in fact the front end has to re-implement the entire page every time, which wastes a lot of manpower.

Functional Requirements

The idea of ​​this project is to develop all components and input them into a unified platform for management. Designers can go to the platform to select components, and preview and adjust the components in real time. What you see is what you get during the whole process, and the platform will make adjustments As a result, a string of code is generated. As long as the code is handed over to the front-end, you can use this string of code to reproduce the component modified by the designer on the platform. You can also copy the html/css/js code of the component with one click and quickly apply it to the project. Go, making the front-end development cost of the component part close to zero. The platform needs to implement the following functions:

  1. Manage components, support classification, search, and sorting

  2. Display components, support online preview/editing of components

  3. Component handover, supports generating component code and reproducing components based on code

  4. Usage statistics, supports statistics on the usage of components to facilitate further optimization Component

Functional Analysis

The first version was implemented using jQuery+template. This technology stack is too flexible. The advantage is that it can meet any needs. It is easy to do, but the disadvantage is that it can be done no matter how you do it. It is not conducive to clarifying your ideas, and it is often accompanied by changes while doing it.

The components are placed in a widgets/folder, which is called a component library. Because it is a pure front-end project without file operation capabilities, the reading of components relies on a static json file, which acts as a component library. Directory, which includes all information such as component classification, label, name, date, etc. The data structure is roughly like this:


[{
 "title": "导航类",
 "list": [{
 "widget": "bread-1",
 "title": "图标面包屑",
 "tag": "面包屑/图标",
 "author": "UI",
 "date": "2015-06-04"
 }, 
 ...]
},
...]
Copy after login

Components are listed in the component library as columns/numbers. It is stored in the form of a folder, and it is agreed to use the storage directory as the component code. For example, component bread-1 means that the storage address of the component is the widgets/bread/1/ folder.

Of course, the internal file structure of the component must also be agreed upon, as follows:


widgets
  |-bread
    |-1
      |-album.jpg   //缩略图
      |-config.json  //配置文件
      |-script.js   //脚本模板
      |-style.css   //样式模板
      `-temp.htm   //界面模板
Copy after login

With these conventions, the program can obtain the information of all components through directory files. The acquisition, display, and retrieval of information and components can be realized.

The most critical thing in the component is the config.json file, which contains the component's configurable items and their default values. The platform will read this configuration file when displaying the component and generate a configuration panel based on the configuration information. Here you can define all the variables in the component interface, style, and script. The configuration file probably looks like this:


{
 "cssConfig": {
 "fontSize": {
  "name": "字号",
  "value": "12px",
  "type": "text"
 },
 ...
 },
 "jsConfig": {
    ...
 },
 "showConfig": {
 "viewWidth": {
  "name": "栅格宽度",
  "value": 12,
  "type": "number"
 },
 ...
 }
}
Copy after login

There are three branches of cssConfig, showConfig, and jsConfig in the configuration file. It is a collection of all variables that can be modified in the component. If you want to apply these variables to the component, you need to use the front-end template engine. Therefore, the three major components of the component are written in template syntax during development. After being parsed by the template engine, they can be Get the actual html/css/js content after configuration. For example, the style template looks like this:


.widget-bread-1 {
  font-size: ${fontSize.value}; 
  color: ${textColor.value}; 
}
.widget-bread-1 a { 
  color: ${textColor.value};
}
.widget-bread-1 a:hover{
  color:${hoverColor.value};
}
.widget-bread-1 .ion { 
  font-size: ${iconSize.value}; 
  margin: 0 ${iconMargin.value};
}
Copy after login

After getting the actual code of the component, just insert the result into the page and Just update it in a timely manner. HTML and CSS can directly replace the text content. Because js is introduced in a modular manner, only the module content is replaced and the module is not overloaded. The entire module must be renamed and replaced as a whole. Therefore, the name of the js module is Randomly.

There will be a problem here. Some components need to be used multiple times in the page, then the js selector of this component will conflict. This problem can be solved with the help of the random name of the js module. We It is agreed that in component development, id is used as a reserved variable, and the platform automatically assigns a random string. This string is the same within the component instance, but will be different when called multiple times. In this way, as long as ${id} is used as the id or class of the component's parent node, This solves the problem of selector conflicts, and it can also be used as the CSS namespace of the component, so that possible CSS naming conflicts can be solved invisible.

The above are the core functions of the project.

In addition, localStorage is used as a storage method to implement stand-alone data statistics, which can collect component usage records of the current browser and the configuration of each use. This is mainly the operation of local storage, but The development of the project itself also uses front-end templates, plus component templates, which will be cached using localStorage after the first load. The caching strategies for these contents are different. User data should be permanently stored, and project templates should be manually updated. Components The template needs to be determined according to the situation. If there is too much stored content, it needs to be cleaned. It is unrealistic to delete them one by one during cleaning. Deleting them all may accidentally damage the storage of other applications. The approach here is to encapsulate the localStorage operation, and the storage method will Add a special prefix before the key. When deleting, you only need to traverse the locally stored key and determine whether it matches the prefix to know whether it is stored within the application. The corresponding value method must also add the prefix to the key in reverse. Take value.

In addition, localStorage only supports string access. In order to facilitate our access to object types, the encapsulation method also supports automatic conversion. However, this conversion cannot be blindly converting characters when encountering an object, and matching when fetching the value. If the object can be transferred, the object will be transferred automatically, because sometimes the user may actually save an object string and want to get it back as is when taking it out. To solve this problem, you need to make a small hack. When the storage method detects the value When it is an object, it will be converted into a string and then an identification string will be spelled in front. The value method will only restore the following string to an object after detecting this identification. Although this method can meet the needs, it is not It is very safe, because this prefix is ​​fixed, and theoretically it is always possible to encounter a lottery winner. I don’t know if there are other better solutions to this problem.

The main function points of the project are these.

Reconstruction

One reconstruction

The first reconstruction only used Vue. During the reconstruction process, the first What I experience is all kinds of conveniences. What I originally had to call the template engine to do is done by the framework. I originally had to bind events in js, but now I can bind them directly in the template, and there are various other syntactic sugars.

Of course, the most important thing is two-way binding. Based on two-way binding, the interface and data can be automatically associated, making people feel that the program has a certain degree of autonomy, but in order to allow this autonomy to operate normally , developers must plan every step in advance, which is less free than jQuery. Take moving bricks as an example. jQuery is like a particularly flexible crane that can lift bricks with ease and move bricks in a fancy way; Vue is like a universal remote control. You tell it that you want to move bricks from a certain place to a certain place. What happens during the process depends on How to deal with it, the bricks can be moved automatically by pressing the button.

Both methods have their own advantages and disadvantages. If the crane is driven well, it can be very flexible. It is easy to avoid pits on the road. The disadvantage is that you have to drive it time and time again. The button can be programmed to run automatically at one time. The disadvantage is that You must inspect the potholes on the road in advance, schedule all other cars, and explain all the situations clearly, otherwise the car will overturn or crash. You will definitely feel this sense of restraint when switching from jQuery to Vue. You must be forced to do so. "Think before you act." You can't get in the car first and then talk about it.

A large part of the work during the reconstruction period is to establish Vue instances, collect data scattered in every corner of js into data, and concentrate the process of operating data into methods bit by bit, and transfer the data The screening process is concentrated into computed. This whole process can clearly review every implementation detail and reflect on whether each implementation method is reasonable. In fact, it is to summarize the original process of driving a crane into remote control buttons one by one. When all After the summary is completed, the Vue example becomes our final project and can be run automatically.

After reconstruction, relying on various functions of Vue has reduced the amount of code in the logical part. Apart from this, there is no improvement to the project itself. Because there is no routing, the problem of losing the status of the refresh page still exists. ; Because Vuex is not used, a data pollution pit is encountered, which can only be solved with deep copy; and the component-based development model makes the code organization more fragmented. These problems require secondary reconstruction.

Second reconstruction

The goal of the second reconstruction is to improve routing, Vuex, code organization, and Wild Dog Cloud backend.

Although I have the experience of the first reconstruction, I am still a little confused at the beginning of the second reconstruction. Which one should be implemented first, routing or Vuex? After thinking about it, what routing does is "tear down", and what Vuex does is "modify". I feel that the workload of dismantling after modification will be smaller, so I use Vuex first.

The concept of Vuex is a bit abstract to understand out of thin air, but once you use it, you feel very comfortable. Moreover, unlike routing, it can be used almost without distinguishing scenarios. After the introduction of Vuex, the problem of data pollution will naturally be solved. Moreover, the action => mutation => store process brought by Vuex will really make things easier once accepted. The process of introducing Vuex is basically to transfer data to the store and disperse the data operations into actions, getters, and mutations. , and at the same time many synchronized data operations are no longer needed, thus reducing the amount of code.

After that, I started to introduce routing. I was not sure how to divide the views at first. The big views must be login, registration, and main interface. The question is whether the main interface needs to be subdivided. In theory, it can be divided into many parts. Details, but based on the actual usage scenarios of the application, it is found that the interface switching is relatively frequent, and the overhead of frequent loading and unloading of components will be very high. Moreover, splitting tightly coupled components into different views requires recording a lot of status information, which is a bit outweighing the gains. In the end I gave up and did not divide the main view further. Considering that the access overlap of the three views is not high, it is natural to make the component load asynchronously, and only load the component when it is accessed. Vue itself supports asynchronous components, so this matter becomes very simple, as long as it can return a Promise, you can get components in any way.

The next step is to connect to Wild Dog Cloud to achieve real user management and data statistics. Wild Dog Cloud can provide a series of functions such as user authentication and data storage. Through it, you can develop a complete WEB using just js. application. In this way, all previous operations on localStorage must be changed to operations on Wild Dog Cloud, and the data becomes more reliable when it reaches the cloud.

At this point, the second reconstruction is completed. The overall business code feels reduced a lot, but the total code volume is estimated to be not much less. After all, three framework files have been added. However, after repeated splitting, the number of files has decreased from The original three or two js have turned into about ten js. For modularization, seajs is used instead of webpack. Because I still have a wait-and-see attitude towards webpack, and I still don’t feel the need to use it. The key is to develop it based on webpack. The code will be mixed with a lot of private stuff, making your code non-native and unable to run without it. I don’t quite accept this. Moreover, in multi-page scenarios, seajs has more advantages than webpack when combined with local caching. Of course, they The difference is just like the difference between jQuery and Vue. They are not essentially the same thing. The key lies in the usage scenario. The one that suits you is the best.

Postscript

After two refactoring practices and pitfalls, I have a deeper understanding of the Vue framework. I want to use Vue flexibly and freely, and have a good understanding of development. There is a minimum requirement for the project architecture capabilities of the project builder. If Vue is to be introduced to the bottom layer, there is also a minimum requirement for the planning capabilities of the infrastructure builder. These are not found in the jQuery technology stack, and the process of using Vue also accepts these constraints. In the process, they can guide developers to establish their own rule system, which is a good thing and a general trend. After all, true freedom only exists in rules.

The complete code of this article can be found on Github.

Related recommendations:

Detailed explanation of using React Family Bucket to build a background management system example

Vue2.0 Web application developed by FamilyMart (refer to Wuji APP)

Example detailed explanation of vue composite component to implement registration form function

The above is the detailed content of Example sharing Vue Family Bucket practical project summary. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!