Front-end development: How to write beautiful Vue and front-end development vue

Source: Internet
Author: User
Tags coding standards opening and closing tags

Front-end development: How to write beautiful Vue and front-end development vue

A few days ago, I heard a sentence about the coexistence of vigor and encouragement, which is terrible and embarrassing. the most helpless and unsolvable words: "After the 90 s, your mid-age crisis has been killed ". This made me very touched. Obviously, this is a bit exaggerated, but now the day-to-day mediocre, blinking effort, the situation will be quietly displayed in the face of this skinny reality. Therefore, it is more and more experienced that, when there is a need to do it in a planned manner, to write, to play, to hi, to make good use of this hormone secretion is still a strong time, to enrich to obtain, discovering and tossing; making your life not only work and melancholy, but also time points and "poetry and distance ". Without analysis, you will know how to do this, efficiently complete the work, and then learn how to live elegantly. Currently, we are still a front-end developer and are using Vue. This article is not only about recording or sharing, but also about a long journey. We hope to discuss and give some advice, improve its effectiveness with knowledge.


 

Note:When I wrote [How to Use Sublime Text elegantly] earlier, although it was still updated since October, it was still far from this topic. Therefore, when talking about the existence of this broad topic, we need to study it in depth, not overnight. Therefore, this article will be updated occasionally, it is also a way to treat procrastination, and also an attempt to restrict the collection of network crawlers.
Update:For how to build a VueJs project, we naturally recommend the official scaffolding vue-cli
For small and medium-sized projects, I am optimistic about poi -- (Delightful web development), which allows you to easily use the current popular framework (such as Vue React ). Even so, many friends in the industry are still not satisfied with the construction of the Vue project. In view of this, based on some past experience, we have designed a set of model-vue-boilerplate-template, for your reference. Of course, I hope you can correct me. It depends onvue-router
,vuex,vue-i18n, Element-ui, and bootstrap libraries.webpack,Eslint,pre-commitAnd so on. Specifically, it calls and uses backend interfaces, applies vuex, shapes view structures, configures routes and multi-language, schedules public methods, and optimizes webpack packaging, based on the premise of convenient development, we have made the corresponding design, hoping that some people will like it; this design reason will be explained in another article; and this design will also, continuous improvement in learning, so stay tuned

Suiyan: As you are a warrior about to fight against the vast army of endless demands, you need not only a good physique, but also a skill: and this software engineering
(Or add algorithms) is like the internal function ().
, It is as good as martial arts moves (solitary nine swords ?); The various tools used should be like a portable tool (Xiao Li feidao ?); That belongs to a set of extreme development processes, that is, the light power (the light God walk ?)...... For example, how many skills are you as a developer?
As mentioned above, this article is intended to be discussed in the following aspects:

How to Use Vue tools

To sharpen the tool first, you must sharpen it first. This is a major advocate of this blog. tools are the first to mention about How to Write Vue elegantly. After all, this is very important; when you choose to use Vue for front-end development, you have agreed to this point: after all, Vue is also written in native Js, while Js is written in C language, C is written in assembly ..... This is no longer the age of farming, and you have not used assembler or C to solve your needs. So, you agree. Does it mean to agree? Let's discuss it together:

Peripherals: In addition to those comfortable mounts and desks, dual-screen display,MacIt is essential for peripherals. As you know, when the code is written in one screen editor, you can see the performance in another screen Chrome, which is efficient, convenient, and comfortable. MacAn elegant lover in the deviceIs a good product at home. If efficiency is not so important in your work environment, or you do not show such generosity, you must be considerate of your energy and time and be brave enough to build your development environment well.

Software: As a developer, your computer and software are like the sword in the samurai hand, helping you kill the existence of the Quartet. So whether it is used to play a prank, to pay tribute to Dota, or to engage in demand, it is very necessary to turn it forward. Therefore, such as Alfred, Brew, Iterm2, Oh-my-zh, Git, and so on are not required. For front-end development, editor and browser configuration and application, especially important (For this reason, many front-end developers have not yet passed the test, just like their level); for browsers, only recommendedChromeNot only browsing or debugging, but also searching. The editor is recommended.SublimeText3AndAtom;VsCodeIt is also very good, and the front-end and back-end writing are very good (visual Google is also pushing it); not recommended for useWebStormIn addition to the anti-human operation design, it does not feel any other memorable points.

Perimeter: Use Vue to develop the front-end. always pay attention to the peripheral Tool System, suchNode,Npm(Yarn),Webpack,GulpAndLodash,superagent,d3And other tool libraries, there is a Vue system itself, suchVue-cli,vue-routerAnd then the extended Vue plug-in.According to Atwood's law:Any application that can be written in JavaScript, will eventually be written in JavaScript.(Translated as follows: Anyone that can be written in JavaScript will be written in JavaScript ). This theory is also applicable to Vue. It is simple and powerful, attracting a lot of ultra-powerful developers or teams and contributing countless useful component libraries to it. For example, ELE. Me's Element-UI, vue-echarts, vue-multiselect ...... For more information, see awesome-vue.

 


(Web Front-end learning and communication group: 328058344 chat prohibited, not welcome !)

 

How to use it effectively-Vue-basics) How to Use Vue beautifully

Software EngineeringAs a programmer, it should have been a good skill. Image[Code Daquan 2]And[Program cleanliness]It must be a good read. Web Front-end development, because of its ease of entry (and strong demand), has brought this line into a lot of sharp gains, but also surprised a lot of "unreadable" code. The front-end development is changing with each passing day. If you cannot grasp it gradually, in the long run, the grievance is not all about others (those who read your code), but more about yourself. To give a simple example, if you cannot learn a good organizational code structure, even if you have a high handwriting architecture, once the project gets bigger, it is still difficult for you to be miserable? As a matter of fact, there are many developers who have failed to develop a good coding literacy. The basis, such as the naming of variable methods, is also shocking. Obviously, this is a behavior that harms people and is bound to be good.

For the team,EslintIt is really a powerful tool to be equipped. Since it is difficult to ensure that everyone is literate, it must be forced as appropriate; at least some messy code should be avoided, so as to be confused. Of course, some people will not be very comfortable at the beginning of use, so the importance of the editor will reflect its value again. This also leads to the topic of automated (semi-) workflows, this will be discussed later.

Basic frontend TechnologyFor a long time, basic skills are very important, especially JavaScript. This is also evident in Vue writing. Others, such as Html and Css, do not need to be said; in addition, Scss and other pre-processors are also used to learn and use them to improve development efficiency and save development costs; after all, only by saving enough time can we do more optimization and save more energy and time. A good cycle can be formed.

Vue BasicsIt is very important to read [Vue. js official tutorials], there are no better tutorials than this. Based on previous experiences, The impatient ones cannot eat hot tofu, And the underperforming ones will eventually be enough. At least at first, you need to read it, otherwise, it will be a waste of time to find out where the problem occurs. In addition, you can find a good micro-project on Github and read it carefully to find a lot of useful methods.

Make full use of configurations, Chapter 4 of code DaquanTable-Driven Method(Table-Driven Methods), it is necessary for programmers to read. In many cases, you can use a query table to simplify the logical and inheritance tree relationships. This is more valuable in team collaboration and the module-based development model. We should make good use of the configuration and separate modules so that there is no strong dependency between them, so that the development process can greatly avoid code conflicts. For example, to understand JavaScript features, you can write the following code:

const files = require.context('.', true, /\.svg$/)const modules = {}files.keys().forEach((key) => {  if (key === './index.js') return  modules[key.replace(/(\.\/|\.svg)/g, '')] = files(key)})export default modules

In this way, you can write a convenient [Icon Component]. You only need to add a new Svg to assets during use, and then enter the corresponding Svg name When referencing the icon, which is very convenient, we can use this configuration to break down and combine modules, which is very convenient.

Vue has three major features, which are very exciting. First, it is bound to two-way data, that is, through the data binding link View and Model, data changes are automatically mapped to View updates. The other is its data-driven component system, which uses a nested component tree to describe the user interface (and a component can correspond to the ViewModel in MVVM ), the third is the single file component format based on the build tool. That is, it provides powerful loader APIs to define the preprocessing logic for different file formats, so that we can integrate CSS and templates, even custom file formats are used as JavaScript modules, which greatly improves code reusability. Based on loader, Webpack can also implement a large number of advanced functions, for example, automatic multipart packaging and loading as needed, automatic locating of image resource references, determining whether to use base64 inline based on image size, and hot replacement of modules during development, etc. Of course, Vue also has several other amazing designs.

In view of this, if you can master the data binding and transmission, component development, and the surrounding Webpack and other related configurations, You can regard the application level as entering a new level. From past experience, this is not an easy task. After all, using this Vue is also aimed at solving the needs, rather than conducting research. Who can say that drivers who drive on the road can understand everything about cars? I believe that for a long time, we must learn and explore these aspects and then use them.

How to use it effectively-Vue-practical components)How to use practical Vue Components

A major feature of Vue is the use of nested component trees to describe the user interface. Therefore, the design and compilation of components are crucial. at least make sure that it is easy to modify and maintain. It is highly reusable and readable, with low coupling, and accepts cooperative development by teams... ... And so on. Once the project is complex, you have to consider the design of the entire architecture in advance to make it clear and reasonable; use of component cache to avoid derivative of excessive components... . The Vue component system is data-driven, so it must take into account data communication among various components to avoid data being operated by multiple parties and difficult to locate bugs.

This is a skill that requires long-term accumulation. However, you only need to pay attention to some content to see its effectiveness. For example, concise and well-known naming, good coding standards, and unified coding style by the Team to ensure code readability. Use design pattern principles, suchSingle Responsibility PrincipleTo split the component into finer-grained parts to ensure a single component function, so as to improve the reuse of the component line.Interface isolation principleThe stable server interface is used to separate the changing modules so that the components can be decoupled. In complex projects, redundancy and inheritance are also required.Rys replacement principle,Dependency inversion principle... . In addition, when learning the optimization provided by Vue itself, such as [routing lazy loading], that is, combining the asynchronous components of Vue and the code splitting feature of Webpack, it is easy to implement lazy loading of routing components, this component is loaded only when accessed to improve page loading efficiency. In addition, the service end is used to implement the first screen rendering and component caching. It is important to note that data communication between components, this will be mentioned in later sections, and we will not repeat it here.

There are many points to learn and explore here. You can see a PPT Vue without cover. js practice: How to Use Vue2.0 to develop rich interactive WEB applications. Many Vue-related points are worth looking. In addition, if you want to write public components for the team, you must remember to attach the corresponding user documents, which is very important. You see, as mentioned above, it is essential to write beautiful Vue (CODE) and learn software design, isn't it? (Web Front-end learning and communication group: 328058344 chat prohibited, not welcome !)

How to use it effectively-Vue-practical communication)How to Use Vue effectively

Earlier, in [Vue data binding], Vue data binding was described in version 1.); Although Vue has already been upgraded to 2.However, although there are many changes in data binding, the overall situation has little impact. for example, fragment instances are no longer allowed; three Mustache syntaxes must be replaced with v-html; and the sequence of v-for parameters must be changed, for details, see [migrate from Vue 1.x]. The data transmission between vue components is discussed here.

After Vue2 removes $ dispatch () and $ broadcast (), it mainly uses prop
(Including v-model Customization) the parent component can pass parameters to the child component, and only one-way transmission is allowed;To prevent reverse impact on the parent component, Vue2 has removed the. once And. sync modifiers. The child component needs to explicitly pass an event instead of relying on Implicit two-way binding.Once you try to directly modify the data of the parent component passed in through props in the component, this will be considered as anti-pattern and the following error is reported:

Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop’s value.

However, if the passed prop itself is a reference-type transfer, such as an object or an array, no matter what the binding method is due to the characteristics of the Data Type itself, it will be two-way binding! These are described in the Vue document-unidirectional data streams. Please refer to this example:

Note that the Vue either listens for changes in the value of the basic data type, or listens for the reference data type.Reference changeTherefore, vue encapsulates a set of methods (including$set,$remove), If you directly change the content of the reference type, even if the data has been modified, but the Vue is not aware of it, the view will not be updated (targeted attribute assignment operations, the set Method of its properties will be called, so Vue will be aware and drive view update ). Here, we need to add that Vue uses Object. defineProperty (ES5 feature) to convert datagetter/setterTo implementwatcher,setterWhen called, re-draw the associated Dom to refresh the view.

Therefore, if you want to change the data that is passed to the parent component, it is best to modify the data that is copied in depth, and pay attention to the gains and losses,Object.assignNot a deep copy, even if you useObject.freeze()Freeze. You can use$emitYou can also use callback Functon. For more information, see the jsfiddle example. Communication between non-Parent and Child components, Vue providesVuexIn the form of State sharing to achieve the same letter, for this point, you should pay attention to consider the balance, from the overall design perspective, to ensure that the necessary to introduce her. If the project is not complex, you can design a setvue-busTo provide a global event center so that global events can be conveniently used just like built-in event streams. Of course, Vue also provides$refsCan be called across layers, orthis.$parent.$parent; Does not mean that recommendations are provided; use as few as possible, unless forced, or go to prank. Of course, you can also use native APIsSessionStorage,LocalStorageAnd so on, to achieve the purpose of communication; for both gains and losses, just strive for a flat Unified Communication Mode. In view of the length, we will not repeat it much.

How to Use Webpack in a beautiful way-Vue) How to Use Vue Webpack

As mentioned above, we recommend using Vue-cli, which has helped us to configure Webpack. When writing a router configuration, you can easily load the routing components, so that the project can be split into several js packets and a slightly larger vendor, which can be loaded as needed during running. That is, we can configure the routing components as follows (of course, we can also divide the components by component blocks ):

Import Frame from '. /.. /views/Frame 'export default {path: '/', component: Frame, children: [{path: '/nicelinks', meta: {title: setTitleLang ('qingqing youcao Xuan ', 'Nice Home blog')}, component: resolve => require (['. /.. /views/Nicelinks '], resolve)}]}

DllReferencePlugin
In additionWebpackThere are a lot of things that need to be optimized to shorten the package build time and improve its size. For exampleDllReferencePluginExtract commonly used files that are not frequently changed and break them into another Unified File (vendor. dll. js). The external chain is introduced as a script. There are many online tutorials. I will not repeat them here.

Webpack-bundle-analyzer
LatestVue-cliIt also injects the [webpack-bundle-analyzer] plug-in (Webpack plug-in and CLI utility), which can display the content bundle as an intuitive tree chart for convenient interaction, let you understand what is actually introduced in your build package. We can use her to find out which modules constitute it, find the wrong module, and optimize it. We canpackage.jsonRun her (npm run analyz) with the following commands. http: // 127.0.0.1: 8888 is enabled by default.

“analyz”: “NODE_ENV=production npm_config_report=true npm run build”

 


 

 

After introducing the DllReferencePlugin plug-in, webpack-bundle-analyzer will add vue in webpack. dll. conf. js. For example, the following configuration is performed:

entry: {   vendor: [     'lodash',     'superagent',     'vue',     'vue-router',     'vue-i18n'     'vuex'   ] }

When you use webpack-bundle-analyzer for analysis, you will find that the Parse Size is 71 KB vue. common. js, will appear in the vendor. xxx. in js, it should not be pushed to the vendor as expected. dll. in js? Speaking of this, to ensure the integrity of the article, I have to mention that after vue2 is upgraded to Version 2.2, eight files are changed:

vue.common.js
vue.esm.js
vue.js
vue.min.js
vue.runtime.common.js
vue.runtime.esm.js
vue.runtime.js
vue.runtime.min.js

The difference between each file in the Vue2 dist directory can be viewed. In addition, the differences between vue and vue are also clarified when building independently-vs-runtime.Vue. common. jsIt is a product of independent build, and the default NPM package exportsRuntimeTo use an independent build (template supported), add the following alias to the webpack Configuration:

resolve: {  alias: {    'vue$': 'vue/dist/vue.common.js'  }}

In this way, in the webpack. dll. conf. inject vue into js configuration, resulting in the vendor. xxx. vue appears in js. common. js, it can be explained that the vue packaging configuration in dll is different from that introduced in resolve. The former is built at runtime by default. If the consistency is ensured, this problem can be solved. This point has been tested and the data obtained is as follows (the resolve configuration is as follows ):

 

In comparison, the difference between the two is greater than 71 KB, which is the difference between vue. common. js Parse Size and vendor. dll. js-27KB, that is, the build Size during runtime. Open the generated vendor-manifest.json, you will also find that the pre-and post-generated vue-related references are:

/node_modules/vue/dist/vue.common.js
./node_modules/vue/dist/vue.runtime.common.js

How to Use Vue Workflow

"Being light does not mean martial arts, but the speed determines the distance between you and me ." -- Bai Feng (Qin shiyue ). The trend of intelligence and automation is becoming more and more obvious. If programmers cannot adapt as soon as possible, the dilemma they face can be imagined. In the near future, blue-collar code migrant workers will inevitably be overwhelmed by the wave of technology. Therefore, this requires practitioners to quickly and accurately solve their needs and keep their knowledge and skills updated. The word "quick" naturally plays a decisive role in business skill proficiency. However, if there is an excellent workflow mechanism, it will inevitably be icing on the cake. This topic is covered by the dot and line. It will change and update continuously in the gradual learning and exploration process. But at least one current criterion is:Even if it cannot be fully automated, it must at least be semi-automated.. (Web Front-end learning and communication group: 328058344 chat prohibited, not welcome !)

 


 

 

Used by many friendshexoTo build a blog;hexoIs based onNode.jsProduct: It is very convenient to post a blog with it. You only needhexo clean,hexo g, hexo dYou can use three commands. If there are more than one piece of data in the article, you have to write it in 20 s.npm, Inpackage.jsAdd vertex names, such;

"scripts": {  "start": "sudo hexo clean && sudo hexo g && sudo gulp && sudo hexo d"}

You only need to runnpm startIt can reduce the time consumption to 2 s, although not much, but it is also an order of magnitude increase, and the cost is only so small, and once and for all. Therefore, it is necessary to give a brief explanation of this, with some meager experience.

  • Although Vue-cli is powerful, it should not be complicated as a basic public utility. You should have your own (Team) scaffolding. When you are about to start a new project, you only need to run the scaffolding to initialize the entire project, instead of copying it a little bit, and then reconfigure it, introduce routing, inject Bootstrap... . The same project should also have a template library that can be generated with one click, or an automatic Json parsing mechanism.

  • Before writing the code, you must reserve the interface, parameters, and returned data with the background er, and generate a visual API document for testing. Nothing is more important than this (if the project exceeds January/person ). Open-source tools like this are also numerous, such as Swagger-Ui.

  • When writing code, you should first think twice before writing. When writing, make sure that the editing tool is sharp, such as retrieval syntax errors, opening and closing tags are complete, and the code is automatically formatted to conform to the agreedEslintRequirement, and make sure that the code is clear and concise. Imagine what if your desk is filled with insects, flies, and mobs all day long?

  • Vue-cliThe agent has been configured, so you don't have to worry about local cross-origin debugging issues. However, you need to configure your own tools to quickly submit valid code. The command line or SourceTree visualization tool is convenient and convenient. You should also usepre-commitTool to perform verification before commit to prevent unauthorized submission and affect teammates.

  • I have experienced the miserable experience of manually testing APK and the difficulty of manual build and release. I think of it as sad. Therefore, listening to repository code changes and automated building are essential for home life. I have also experienced various amazing ways to close bugs in my career. I admit that it takes more time to do this than to solve the so-called Bug. These are nothing more than the criticism of the team's short knowledge at that time. Now, the team uses jenkins and GitLab to work together without the pain and emotion.

  • What is it to write beautiful Vue? It not only lies in the beauty of code, but also in its efficiency and resource saving. Data-driven Vue itself is very efficient, but the code written using C is not necessarily more efficient than JavaScript. This variable is written by different people. Therefore, in addition to the Code Review Code, there must also be a set of effective comprehensive analysis methods. In order to ensure that the Code is loaded on demand, Css is properly written and referenced, where this is, and so on.

  • What is it to write beautiful Vue? It also lies in its reliability and stability, and these are ultimately to be reflected in the product; therefore, good products must not only be equipped with access conditions, behavior analysis, event tracking, but also error reporting. Early on, I used the simple book, a read/write integrated product. Now, it is not only filled with chicken soup and titles, but also with various bugs, especially on Web pages (Mac mini, pc), no feedback, it's terrible. Why? It is determined that they did not use tools similar to sentry.

  • Background TechnologyThe front-end of the backend is not a good designer. It makes sense to say that it seems ridiculous. Nowadays, the popular frontend and backend separation development mode is easier to cooperate and more efficient if both sides of their respective roles can understand each other's technologies. In more cases, it is also common for front-end writing to the background out of some needs. It is also a good thing for individuals. Some personal products have been written recently. If you are looking for background development assistance, you will certainly have less trouble than learning how to write the backend. It is not a long term. Even if this is not the case, we also need to understand background technologies to solve Vue SEO and improve the rendering speed and perform Vue SSR.

  • Design ProblemsThis design includes not only code structure, layers, interfaces, but also page-related design for front-end practitioners. For example, the personal product being developed: the chain of the city (English Name: nice links), because of the lack of Design Aesthetics, it can be said that it is difficult to initially shape the application, but from the perspective of the visual effect, I always feel that the difference is still waiting for depletion. Even if there is no similar requirement, there is already a designer drawing for the page. To restore the page perfectly, this design-related literacy is indispensable. After all, the product is finally presented to the user, depends on front-end developers.

Conclusion

"You have to be a programmer first, and then a front-end programmer". This point of view makes sense and will become more and more obvious over time. Therefore, this article is not limitedVueThe deeper intention of learning and applying is to use the current popular frameworkVueTo break through the interface, we will share some development experiences, programming experiences, and product user experience on the front end. Obviously, this is just the tip of the iceberg. Moreover, the front-end development is so prosperous that it is difficult to cover all aspects. Only by adhering to the mindset of continuous learning, embracing changes, and looking forward to the future can we go further in this surging wave. When talking about this, it is necessary to share with you the latest [advance version of the front-end resource tutorial], which has been collecting excellent articles on current and future technologies, as well as the essence of tools, optimization, testing, and security, the aim is to facilitate front-end learning, skill improvement, Horizon expansion, and data search; Interested friends, you can take a closer look, or further assist with supplements and corrections so that they can serve more people.



Author: laifeng love frontend
Link: http://www.jianshu.com/p/a496343dd12a
Source: Simplified book
Copyright belongs to the author. For commercial reprint, please contact the author for authorization. For non-commercial reprint, please indicate the source.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.