In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly shows you "what are the vue knowledge points", the content is easy to understand, clear, hope to help you solve your doubts, the following let the editor lead you to study and learn "what are the vue knowledge points" this article.
First, front-end core analysis 1.1, overview
Soc principle: the principle of separation of concerns
Vue's core library only focuses on the view layer, making it easy to integrate with third-party libraries or existing projects.
HTML + CSS + JS: view: show it to the user and refresh the data given by the background
Network communication: axios
Page jump: vue-router
State management: vuex
Vue-UI: ICE, Element UI
1.2, front-end three elements
HTML: hypertext markup language (Hyper Text Markup Language), which determines the structure and content of a web page
CSS (presentation): cascading style sheets (Cascading Style Sheets) to set the presentation style of the web page.
JavaScript (behavior): a weakly typed scripting language whose source code does not need to be compiled, but is interpreted and run by the browser to control the behavior of web pages
1.3. structural layer (HTML)
Too simple, slightly
1.4.presentation layer (CSS)
CSS cascading stylesheet is a markup language, not a programming language, so it cannot customize variables, references, etc., in other words, it does not have any syntax support. Its main drawbacks are as follows:
The syntax is not strong enough, such as the inability to nest writing, resulting in the need to write a lot of repetitive selectors in modular development
Without variables and reasonable style reuse mechanism, logically related attribute values must be output repeatedly in the form of literals, which makes it difficult to maintain.
This has caused us to increase a lot of workload in our work for no reason. To solve this problem, front-end developers will use a tool called CSS preprocessor to provide the missing style layer reuse mechanism of CSS, reduce redundant code, and improve the maintainability of style code. It greatly improves the development efficiency of the front end in terms of style.
What is a CSS preprocessor
CSS preprocessor defines a new language, its basic idea is to use a special programming language, add some programming features to CSS, take CSS as the target to generate files, and then developers only need to use this language for CSS coding. Translated into easy-to-understand words is "using a special programming language, Web page style design, and then converted into a normal CSS file through the compiler for the project to use."
What are the commonly used CSS preprocessors
SASS: based on Ruby, through server-side processing, powerful. The parsing efficiency is high. Need to learn Ruby language, it is more difficult to use than LESS.
LESS: based on NodeJS, handled by the client, easy to use. The function is simpler than SASS and the parsing efficiency is lower than SASS, but it is sufficient in actual development, so we backstage staff are recommended to use LESS if they need it.
1.5. Behavior layer (JavaScript)
JavaScript is a weakly typed scripting language whose source code does not need to be compiled before it is sent to the client for operation. Instead, the character code in text format is sent to the browser, which is interpreted and run by the browser.
Native native JS development
Native JS development, that is, let's develop in accordance with the [ECMAScript] standard, referred to as ES, is characterized by the support of all browsers. So far, the ES standard has been released as follows:
ES3
ES4 (internal, not officially released)
ES5 (full browser support)
ES6 (commonly used, current mainstream version: webpack is packaged into ES5 support)
ES7
ES8
ES9 (draft stage)
The difference is to gradually add new features.
TypeScript Microsoft standard
TypeScript is a free and open source programming language developed by Microsoft. It is a superset of JavaScript and essentially adds optional static types and class-based object-oriented programming to the language. Led by Anders Hellsberg (father of C #, Delphi, TypeScript; founder of .NET). The characteristic of this language is that in addition to the features of ES, it also includes many new features that are not within the scope of the standard, so many browsers can not directly support TypeScript syntax and need to be compiled (compiled to JS) to be executed correctly by browsers.
JavaScript framework
JQuery: the well-known JavaScript library has the advantage of simplifying DOM operations, while the disadvantage is that DOM operations are too frequent, affecting front-end performance; in front-end eyes, it is used only for compatibility with IE6,7,8
The front-end framework acquired by Angular:Google, developed by a group of Java programmers, is characterized by moving the background MVC model to the front end and adding the concept of modular development, in cooperation with Microsoft, using TypeScript syntax development; friendly to background programmers, not very friendly to front-end programmers; the biggest disadvantage is that the version iteration is unreasonable (for example, generation 1-> 2, except for the name, it is basically two things Angular6 has been launched by the time of publication of the blog)
React:Facebook, a high-performance JS front-end framework, is characterized by the introduction of a new concept [virtual DOM] to reduce real DOM operations and simulate DOM operations in memory, effectively improving the front-end rendering efficiency; the disadvantage is that it is complex to use, because you need to learn an additional [JSX] language.
Vue: a progressive JavaScript framework, which means to gradually implement new features, such as modular development, routing, state management, and so on. It combines the advantages of Angular (Modularization) and React (Virtual DOM).
Axios: front-end communication framework; because the boundary of Vue is very clear, it is to deal with DOM, so it does not have the communication capability, so you need to use an additional communication framework to interact with the server; of course, you can also directly choose to use the AJAX communication function provided by jQuery.
II. Front-end Development History 2.1and UI Framework
Ant-Design: a React-based UI framework produced by Alibaba
ElementUI, iview, ice: ele.me, UI framework based on Vue
An open source toolkit for front-end development launched by BootStrap:Teitter
AmazeUI: also known as "Girl UI", a HTML5 cross-screen front-end framework
2.2.The JavaScript build tool
Babel:JS compilation tool, mainly used for new ES features that browsers do not support, such as compiling TypeScript
WebPack: module baler, the main function is to pack, compress, merge and load sequentially
Note: the above knowledge points have sorted out all the skills required for WebApp development.
2.3. Three ends are the same.
Mixed development (Hybrid App)
The main purpose is to achieve the unification of a set of codes (PC, Android:.apk, iOS:.ipa) and be able to call the underlying hardware of the device (such as sensor, GPS, camera, etc.). There are two main packaging methods:
Cloud packaging: HBuild-> HBuildX,DCloud products; API Cloud
Local packing: Cordova (formerly PhoneGap)
WeChat Mini Program
For details, see Wechat's official website. Here is an introduction to a framework that is convenient for WeChat Mini Programs's UI development: WeUI
2.4. Back-end technology
Front-end staff also need to master some back-end technology in order to facilitate development, but we Java background staff know that the background knowledge system is extremely large and complex, so in order to facilitate front-end staff to develop background applications, there is a technology like Node JS. The author of Node JS has claimed that he has given up Node JS (saying that the poor performance of the architecture, coupled with the clunky node modules, may upset the author) and begin to develop the De no of a new architecture.
Since it is a background technology, it certainly requires frameworks and project management tools. The Node JS framework and project management tools are as follows:
Express:Node JS framework
Simplified version of Koa:Express
NPM: an integrated project management tool, similar to Maven
An alternative to YARN:NPM, similar to the relationship between Maven and Gradle
2.5, mainstream front-end framework
Vue.js
IView
Iview is a powerful Vue-based UI library. There are many practical basic components that are richer than those of element ui, mainly serving the middle and background products of the PC interface. Using single-file Vue component development model based on npm+webpack+babel development, support ES 2015 high-quality, feature-rich and friendly API, free and flexible use of space.
Official website address
Github
Iview-admin
Note: it belongs to the front-end mainstream framework and can be considered for use when selecting the model. The main feature is that the mobile terminal supports more.
Element UI
Element is an open source Vue UI component library maintained at the front end of ele.me. It has a full range of components and basically covers all the components needed in the background. The documentation is detailed and the examples are rich. Mainly used for the development of PC-side pages, is a relatively high-quality Vue UI component library.
Official website address
Git hub
Vue-element-admin
Note: it belongs to the front-end mainstream framework and can be considered when selecting the model. The main feature is that there is more support on the desktop side.
ICE
Feibing is a React/Angular/Vue-based application solution for Alibaba's team. Within Alibaba, there are already more than 270 projects from almost all BU. Feibing includes a complete link from the design side to the development side to help users quickly build their own mid-background applications.
Address on the official website.
Git hub
Note: the main component is still React, and the support for Vue before updating the blog on February 17, 2019 is not perfect, and it is still in the wait-and-see stage.
VantUI
Vant UI is a Vue component library implemented by the like front-end team based on the unified specification of likes, providing a complete set of UI basic components and business components. Through Vant, you can quickly build a page with a unified style and improve the efficiency of development.
Official website address
Github
AtUI
At-ui is a front-end UI component library based on Vue 2.x, mainly used for the rapid development of PC website products. It provides a set of n pm+web pack+babel front-end development workflow, CSS style independent, even if the use of different framework implementations can maintain a unified UI style.
Official website address
Git hub
Cube Ul
Cube-ui is an exquisite mobile component library based on Vue js developed by Didi team. It supports on-demand introduction and post-compilation, lightweight and flexible, strong expansibility, and can easily realize secondary development based on existing components.
Official website address
Github
Mixed development
Flutter
Flutter is Google's mobile UI framework, which can build high-quality native applications on Android and iOS in a very short time. Flutter works with existing code, it is used by developers and organizations around the world, and Flutter is free and open source.
Official website address
Github
Note: produced by Google, the main feature is to quickly build native APP applications, such as mixed applications, this framework is a required framework
Lonic
Lonic is both a CSS framework and a Javascript UI library. Lonic is the most potential HTML 5 mobile application development framework at present. Build applications through SASS, which provides a number of UI components to help developers develop powerful applications. It uses the JavaScript MV VM framework and Angular JS/Vue to enhance the application. Provide two-way binding of data, and use it as a common choice for both Web and mobile developers.
Official website address
Official website document
Git hub
WeChat Mini Program
Mpvue
Mpvue is a front-end framework developed by Meituan to develop Mini Program using Vue.js. It currently supports WeChat Mini Programs, Baidu Intelligent Mini Program, Toutiao Mini Program and Alipay Mini Program. The framework is based on Vue.js, and the implementation of the runtime framework runtime and the code compiler compiler are modified to make it run in the Mini Program environment, thus introducing the Vue.js development experience for Mini Program development.
Official website address
Git hub
Remarks: complete Vue development experience, well and support multi-platform Mini Program development, recommended
WeUI
WeUI is a basic style library consistent with Wechat's native visual experience, tailored by Wechat's official design team for the Wechat web page and WeChat Mini Programs, making the user perception more unified. Contains button, cell, dialog, toast, article, icon and other elements.
Official website address
Github
Third, understand the evolution of the separation before and after.
Why do you need front and back separation?
3.1.The back-end-oriented MVC era
In order to reduce the complexity of development, the back end is the starting point, for example, the use of Struts, Spring MVC and other frameworks is the MVC era of the back end.
Take the SpringMVC process as an example:
Initiate a request to the front-end controller (Dispatcher Servlet)
The front-end controller requests HandlerMapping to find Handler, which can be found according to xml configuration and comments.
Processor mapper HandlerMapping returns Handler to the front-end controller
The front-end controller calls the processor adapter to execute the Handler
Processor adapter to execute Handler
Handler execution completed returns ModelAndView to the adapter
The processor adapter returns ModelAndView,ModelAndView to the front controller, which is an underlying object of the SpringMvc framework, including Model and View
The front-end controller requests the view parser to parse the view and resolve it to a real view (JSP) according to the logical view name.
The view parser returns View to the front-end controller
The front controller performs view rendering, which populates the model data (in the ModelAndView object) into the request field
The front-end controller responds to the result to the user
Advantages
MVC is a very good collaboration model, which can effectively reduce the coupling of code and architecturally let developers know where the code should be written. In order to make View more pure, you can also use template engines such as Thyme leaf and Frree marker to make it impossible to write Java code into the template and make the division of labor between the front and back ends clearer.
Shortcoming
Front-end development is heavily dependent on the development environment, and the development efficiency is low. Under this architecture, there are two modes of front-end collaboration:
The first is to write DEMO at the front end, and then let the back end set up the template. The advantage is that DEMO can be developed locally and is very efficient. The deficiency is that the back-end set template is still needed, which may be wrong, and the front end needs to be determined after the set is done. the cost of communication and adjustment back and forth is relatively high.
Another collaboration model is that the front end is responsible for all browser-side development and server-side View layer template development. The advantage is that the UI-related code is written at the front end, and the back end does not need to pay too much attention. The deficiency is that the front-end development is heavily bound to the back-end environment, which has become an important factor affecting the efficiency of front-end development.
The front and back end responsibilities are entangled: the template engine is powerful and can still implement a variety of business logic through the context variables you get. In this way, as long as the front end is weak, it is often required by the back end to write a lot of business code in the template layer, and there is a big gray area is Controller. Functions such as page routing are supposed to be the most concerned by the front end, but they are implemented by the back end. Controller itself is often entangled with Model, and the gnawing business code often appears in the Controller layer. These problems can not all be attributed to the literacy of programmers, otherwise JSP is enough.
Limitations to the frontend: the space for performance optimization in the frontend is very limited, so we often need back-end cooperation, but due to the limitations of the back-end framework, it is difficult for us to use [Comet], [Big Pipe] and other technical solutions to optimize performance.
Note: during this period (before 2005), including the early JSP, PHP can be called the Web 1.0 era. I'd like to say here that if you are a beginner in Java, please don't take some old technologies seriously, such as JSP, because times are changing, technology is changing, and everything is changing (to quote Zuckerberg: the only constant is change itself) When we go to do practical training for the university, some students will think that we do not talk about any practical information, but it is not. It can only be said that the practical information you know is already out of date for the market.
3.2.Based on the SPA era brought by AJAX
Back in 2005, An OAX (Asynchronous JavaScript And XML, asynchronous JavaScript and XML, old technology and new usage) was formally proposed and began to use CDN as static resource storage, so there was the era of SPA (Single Page Application) single-page application of JavaScript King's return (before which JS was used to post dog skin plaster advertisements on the web).
Advantages
In this mode, the division of labor between the front and back ends of * * is very clear, and the key cooperation point between the front and rear ends is the AJAX interface. * * it looks so wonderful, but in retrospect, it's not much different from the era of JSP. The complexity moves from the JSP of the server to the JavaScript of the browser, and the browser becomes very complex. Similar to Spring MVC, a hierarchical architecture on the browser side began to emerge in this era:
Shortcoming
Front-end interface agreement: if the back-end interface is a mess, if the back-end business model is not stable enough, then the front-end development will be very painful; many teams have similar attempts to do it through interface rules, interface platform, and so on. With the interface rules precipitated with the back end, it can also be used to simulate data, so that the front end and back end can achieve efficient parallel development after the agreed interface.
Complexity control of front-end development: SPA applications are mostly functional interactive, and it is normal for JavaScript code to exceed 100, 000 lines. It is not easy to organize a lot of JS code, bind to the View layer, and so on.
3.3.The front-end-oriented MV* era
The MV* mode here is as follows:
MVC (synchronous communication primarily): Model, View, Controller
MVP (Asynchronous Communication primarily): Model, View, Presenter
MVVM (Asynchronous Communication primarily): in order to reduce the complexity of front-end development, Model, View and View Model have emerged a large number of front-end frameworks, such as Angular JS, React, Vue.js, Ember JS, etc. The general principle of these frameworks is to layer by type, such as Templates, Controllers, Models, and then split in the layer, as shown below:
Advantages
The responsibilities of the front and back end are clear: the front end works on the browser side and the back end works on the server side. A clear division of labor can make the development parallel, the simulation of test data is not difficult, and the front end can be developed locally. The back-end can focus on the processing of business logic and output RESTful and other interfaces.
The complexity of front-end development can be controlled: the front-end code is heavy, but reasonably layered, so that the front-end code can do its own job. This piece is very interesting, such as the selection of template features, there are a lot of exquisite. It is not the stronger the better, what to restrict, what freedom to leave, how the code should be organized, all of which take the thickness of a book to explain.
Deployment is relatively independent: you can quickly improve product experience disadvantages
The code cannot be reused. For example, the back-end still needs to do all kinds of verification on the data, and the verification logic cannot reuse the code on the browser side. If it can be reused, the back-end data validation can be relatively simple.
All the steps are different, which is bad for SEO. The server side is often required to do synchronous rendering of the degradation scheme.
Performance is not the best, especially in the mobile Internet environment.
SPA can not meet all the needs, there are still a large number of multi-page applications. URL Design needs the cooperation of the back end, and the front end cannot fully control it.
3.4.The full stack era brought by Node JS
The front-end-based MV* model solves a lot of problems, but as mentioned above, there are still many shortcomings. With the rise of Node JS, JavaScript began to have the ability to run on the server. This means that there can be a new R & D model:
In this R & D model, the responsibilities of the front and back end are very clear. For the front end, the two UI layers perform their respective functions:
Front-end Ul layer handles the presentation logic of the browser layer. Through the CSS rendering style, adding interactive features through JavaScript, the generation of HTML can also be placed on this layer, depending on the application scenario.
Back-end Ul layer handles routing, templates, data acquisition, Cookie, and so on. Through routing, the front end can finally control the URL Design independently, so that whether it is a single-page application or a multi-page application, the front end can be regulated freely. The back end can finally get rid of the strong focus on presentation and focus on the development of the business logic layer.
Through Node, the WebServer layer is also JavaScript code, which means that part of the code can be reused before and after, scenarios requiring SEO can be rendered synchronously on the server side, and the performance problems caused by too many asynchronous requests can also be alleviated through the server side. The deficiency of the former model can almost be solved perfectly through this model.
Compared with the JSP model, the full stack model looks like a return, and it is indeed a return to the original development model, but a spiral upward return.
The full-stack model based on Node JS still faces many challenges:
The front end needs to have a better understanding of server-side programming. Such as the mastery of network knowledge such as TCP/IP.
Efficient communication between Node JS layer and Java layer. In Node JS mode, it is all on the server side, so RESTful HTTP communication may not be efficient, and communication through SOAP and other ways is more efficient. Everything needs to move forward in verification.
A skilled understanding of the department and operation and maintenance needs more knowledge and practical experience.
How to make the transition of a large number of problems left over from history. This may be the biggest resistance.
Note: seeing this, I believe many students can understand why I always say in class: "it is difficult for front-end programmers to learn backstage, but it is easy for us back-end programmers to learn anything." it is because we back-end programmers have a relatively perfect knowledge system.
Full stack! So Easy!
3.5. Summary
To sum up, whether the model or technology is good or bad, there is no difference between good and bad, only whether it is suitable or not; the development idea of separation of front and rear is mainly based on Soc (principle of separation of concerns), and all the above modes make the responsibilities of the front and back end clearer and the division of labor more reasonable and efficient.
The first Vue program 4.1.What is MVVM
MVVM (Model-View-ViewModel) is a software design pattern developed by Microsoft WPF (used to replace WinForm, which used to be used to develop desktop applications) and Ken Cooper and Ted Peters, architects of Silverlight (similar to Java Applet, simply running WPF on browsers), is an event-driven programming approach that simplifies the user interface. Published by John Gossman (also the architect of WPF and Sliverlight) on his blog in 2005.
MVVM is derived from the classic MVC (Model-View-Controller) mode. The core of MVVM is the ViewModel layer, which is responsible for transforming data objects in Model to make the data easier to manage and use. Its functions are as follows:
This layer is bidirectional data binding to the view layer upward.
Down to the Model layer for data exchange through interface request
MVVM is quite mature, mainly used but not just in the development of web applications. The popular MVVM framework is Vue.js,Anfular JS.
4.2.Why use MVVM
Like the MVC pattern, the main purpose of the MVVM pattern is to separate the View from the Model, which has several major benefits
Low coupling: views (View) can be changed and modified independently of Model, a ViewModel can be bound to different View, Model can not change when View changes, and View can not change when Model changes.
Reusable: you can put some view logic in a ViewModel and let many View reuse this view logic.
Independent development: developers can focus on business logic and data development (ViewMode), designers can focus on page design.
Testable: interfaces have always been difficult to test, but now tests can be written for ViewModel.
(1) View
View is the view layer, which is the user interface. The front end is mainly built by HTH L and csS. In order to more easily display the data of vi eu to del or Hodel layer, there have been a variety of front and back-end template languages, such as FreeMarker,Thyme leaf and so on. Each major MV VM framework, such as Vue.js.Angular JS, EJS and so on, also has its own built-in template language for building user interfaces.
(2) Model
Model refers to the data model, generally refers to the back-end of a variety of business logic processing and data manipulation, mainly around the database system. The difficulty here mainly lies in the need to agree on unified interface rules with the front end.
(3) ViewModel
ViewModel is a view data layer generated and maintained by the front-end developer organization. In this layer, the front-end developers transform the Model data obtained from the back-end and do secondary encapsulation to generate a view data model that conforms to the expected use of the View layer.
What needs to note is that the data model encapsulated by View Model includes two parts: the state and behavior of the view, while the data model of the Model layer contains only state.
For example, what is shown in this part of the page, and what is shown in that part, all belong to the view state (presentation).
What happens when the page is loaded, what happens when you click on this piece, and what happens when this piece scrolls are all view behaviors (interactions).
View state and behavior are encapsulated in View Model. This encapsulation allows View Model to fully describe the View layer. Due to the implementation of two-way binding, the content of View Model will be displayed in the View layer in real time, which is exciting because front-end developers no longer have to inefficiently and hassle to update views by manipulating DOM.
MVVM framework has done the dirtiest and most tiring piece, we developers only need to deal with and maintain View Model, update the data view will automatically be updated accordingly, the real implementation of event-driven programming.
The View layer does not show the data of the Model layer, but the data of the ViewModel, and ViewModel is responsible for interacting with the Model layer, which completely decouples the View layer and the Model layer. This decoupling is very important, and it is an important part of the implementation of the front and back end separation scheme.
4.3 、 Vue
Vue (pronunciation / vju/, is similar to view) is a progressive framework for building a user interface, released in February 2014. Unlike other large frameworks, Vue is designed to be applied layer by layer from the bottom up. Vue's core library only focuses on the view layer, which is not only easy to use, but also easy to integrate with third-party libraries (such as vue-router,vue-resource,vue x) or existing projects.
(1) the implementer of the MVVM model
Model: model layer, where JavaScript objects are represented
View: view layer, which represents DOM (elements of the HTML operation)
ViewModel: the middleware that connects views and data. Vue.js is the implementer of the ViewModel layer in MVVM.
In MVVM architecture, data and view are not allowed to communicate directly, only through ViewModel, and ViewModel defines an Observer observer.
ViewModel can observe the changes in the data and update the corresponding content of the view.
ViewModel can listen for changes in views and notify data changes.
At this point, we understand that Vue.js is an implementer of MV VM, and his core is to implement DOM snooping and data binding.
(2) Why use Vue.js
Lightweight, small size is an important indicator. There is only more than 20 kb after Vue.js compression (56kb after Angular compression and 44kb + after Angular compression)
Mobile first. More suitable for mobile, such as Touch events on mobile
Easy to use, smooth learning curve, complete documentation
Absorbs the strengths of Angular (modularization) and React (virtual DOM), and has its own unique features, such as: computational properties
Open source, high community activity
4.4. the first Vue program
[description] IDEA can install plug-ins for Vue!
Note: Vue does not support IE 8 and below because Vue uses ECMAScript 5 features that IE 8 cannot simulate. But it supports all browsers that are compatible with ECMAScript 5.
(1) download address
Development version
Contains complete warning and debug modes: https://yuejs.org/js/vue.js
Deleted warning, 30.96KB min+gzip:https://vuejs.org/js/vue.min.js
CDN
(2) Code writing
The core of Vue.js is to implement the MVVM pattern, and her role is the View Model layer, so the so-called first application is to show her data binding function. The operation flow is as follows:
1. Create a HTML file
Title
2. Introduce Vue.js
twelve
3. Create a Vue instance
Var vm = new Vue ({el: "# app", / * Model: data * / data: {message: "hello,vue!"}})
Description:
El: ID of the'# vue': binding element
Data: {message:'Hello Hello Vue'}: there is a property named message in the data object and the initial value is set!
4. Bind data to page elements
{{message}}
Description: only need to use double curly braces in the bound element to wrap the attribute named message created by Vue to achieve the data binding function and achieve the effect needed by the View Model layer, is it very similar to the EL expression?
(3) complete HTML
Title {{message}}
Var vm = new Vue ({el: "# app", / * Model: data * / data: {message: "hello,vue!"}})
(4) testing
In order to more intuitively experience the data binding features brought about by Vue, we need to test it in the browser. The operation process is as follows:
1. Run the first Vue application on the browser and enter the developer tool
2. Enter vm.message='HelloWorld', in the console and enter, and you will find that the content displayed in the browser will directly become HelloWorld.
can directly enter vm.message in the console to modify the value, and data can be omitted in the middle. In this operation, I did not take the initiative to operate DOM, so that the content of the page has been changed, which is achieved with the help of Vue's data binding function; MV VM mode requires that the View Model layer is to use observer mode to achieve data monitoring and binding, so as to achieve fast response between data and view.
Basic grammar instructions 4.1and v-bind
We have successfully created the first Vue application! This looks very similar to rendering a string template, but Vue does a lot of work behind it. Now that the data and DOM have been linked, everything is responsive. We operate object properties in the console, and the interface can be updated in real time!
we can also use v-bind to bind element properties!
Code on
Title hover for a few seconds to see the tips for dynamic binding here!
Var vm = new Vue ({el: "# app", / * Model: data * / data: {message: 'page loaded in' + new Date (). ToLocaleString ()}})
The v-bind and so on you see are called instructions. Instructions are prefixed with v to indicate that they are special features provided by Vue. As you may have guessed, they will apply special responsive behavior to the rendered DOM here, which means: "keep the title property of this element node consistent with the message property of the Vue instance."
if you open the browser's JavaScript console again and type app, message=' New message', you will once again see that the HTML bound with the title feature has been updated.
4.2 、 v-if, v-else
What is a conditional judgment statement, there is no need for me to explain it, the following two attributes!
V-if
V-else
Upper code
Title Yes No
Var vm = new Vue ({el: "# app", / * Model: data * / data: {type: true}})
Test:
1. Run on the browser and open the console!
two。 Enter vm.ok=false in the console and enter, and you will find that the content displayed in the browser will directly become NO.
Note: binding data using the vMMI * attribute does not require double curly braces to wrap
V-else-if
V-if
V-else-if
V-else
Note: the three equal signs in JS indicate absolute equality (that is, the data and type should be equal to the code):
Title A B D C
Var vm = new Vue ({el: "# app", / * Model: data * / data: {type:'A'}}); 4.3, v-for
V-for
Format description
{{item.message}}-{{index}}
123456
Note: items is an array, and item is an alias for the iteration of array elements. The syntax of the Thymeleaf template engine we learned later is very similar to this!
Code on :
Title {{item.message}}-{{index}}
Var vm = new Vue ({el: "# app", / * Model: data * / data: {items: [{message:' crazy god said Java'}, {message:' crazy god said front end'}, {message:' crazy god said operation and maintenance'}]})
Test: type vm.items.push ({message:' operation and maintenance'}) in the console, try to add a piece of data, and you will find that the content displayed in the browser will add a crazy operation and maintenance staff.
4.4 、 v-on
V-on snooping event
emsp; events include events from Vue and some events from the front-end page itself! Our click here is an event of vue, which can be bound to a method event in methods in Vue!
Code on :
Title asked me.
Var vm = new Vue ({el: "# app", data: {message:'Hello World'}, methods: {sayHi:function (event) {/ / 'this' points to the current Vue instance alert (this.message);} in the method)
Click test
There are also some basic ways to use Vue. If you need it, you can follow the official documentation, because we have seen almost all of these basic instructions. Master the way of learning!
Form double binding, component 6.1, what is two-way data binding
Vue.js is a MV VM framework, that is, two-way data binding, that is, when the data changes, the view changes, and when the view changes, the data changes synchronously. This is the essence of Vue.js.
is worth noting that when we talk about two-way data binding, it must be that non-UI controls for UI controls do not involve two-way data binding. One-way data binding is a prerequisite for using state management tools. If we use vue x, then the data flow is also singleton, which will conflict with two-way data binding.
(1) Why to realize two-way data binding
In Vue.js, if you use vuex, the data is actually unidirectional. The reason why it is said to be bidirectional data binding is that it uses UI controls. For us to deal with forms, Vue.js bidirectional data binding is particularly comfortable. That is, the two are not mutually exclusive, and a single item is used in the global data flow to facilitate tracking; the local data flow is bidirectional, which is simple and easy to operate.
6.2. Use two-way data binding in a form
You can use the v-model instruction to create two-way data bindings on forms and elements. It automatically selects the correct method to update the element based on the control type. Magical as it is, v-model is essentially nothing more than grammatical candy. It is responsible for listening to user input events to update data, and to do some special handling for some extreme scenarios.
Note: v-model ignores the initial values of the value, checked, and selected properties of all form elements and always uses the data of the Vue instance as the data source. You should declare the initial value in the data option of the component through JavaScript!
(1) single-line text entered by Title: {{message}}
Var vm = new Vue ({el: "# app", data: {message: ""}}); (2) Multiline Title: multiline text: multiline text is: {{pan}}
Var vm = new Vue ({el: "# app", data: {message: "Hello hello!"}); (3) single check box Title single check box: {{checked}}
Var vm = new Vue ({el: "# app", data: {checked:false}}); (4) multiple check boxes Title multiple check boxes: value selected by Jack Jack Mike: {{checkedNames}}
Var vm = new Vue ({el: "# app", data: {checkedNames: []}}); (6) Radio button Title radio box button One Two selected value: {{picked}}
Var vm = new Vue ({el: "# app", data: {picked:'Two'}}); (7) drop-down box Title drop-down box:-please select-A B C D value: {{pan}}
Var vm = new Vue ({el: "# app", data: {pan: "A"}})
Note: the initial value of the v-model expression does not match any options, and the meta system will be rendered in an "unchecked" state. In iOS, this makes it impossible for the user to select the first option, because in this case, iOS does not trigger the change event. Therefore, it is more recommended to provide a disable option with a null value as above.
6.3. What are components
Components are reusable Vue instances. To put it bluntly, they are a set of templates that can be reused. They are similar to JSTL's custom tags, Thymeleal's th:fragment and other frameworks. Usually, an application is organized in the form of a nested component tree:
For example, you may have components such as headers, sidebars, content areas, and so on, each of which contains other components such as navigation links and blog posts.
(1) the first Vue component
Note: in the actual development, we will not use the following way to develop components, but using vue-cli to create, vue template file development, the following methods are just to let you understand what components are.
uses the Vue.component () method to register the component in the following format:
/ / register the component Vue.component ("pan", {template:'Hello'}) first; / / instantiate Vue var vm = new Vue ({el: "# app",})
Description:
Vue.component (): register the component
Pan: the name of the custom component
Template: a template for a component
(2) use props attribute to pass parameters
There is no point in using the component as above, so we need to pass parameters to the component, and we need to use the props property at this point!
Note: the value in the props attribute under the default rule cannot be uppercase.
Title
/ / define component Vue.component ("pan", {props: ['panh'], template:' {{panh}}'}); var vm = new Vue ({el: "# app", data: {items: ["java", "Linux", "front end"]}})
Description:
V item in items for = "item in items": traverses the array named items defined in the Vue instance and creates the same number of components
Vmurbinditem panh = "item": bind the traversed item item to the props definition attribute named item in the component; the panh to the left of the = sign is the property name defined by props, and the right is the value of the traversal item item in the component
7. Axios Asynchronous Communication 7.1.What is Axios
Axios is an open source asynchronous communication framework that can be used in browsers and Node JS. Its main role is to implement AJAX asynchronous communication. Its features are as follows:
Create a XMLHttpRequests from a browser
Create a http request from node.js
Support for Promise API [chain programming in JS]
Intercept requests and responses
Convert request data and response data
Cancel the request
Automatic conversion of JSON data
The client supports defense against XSRF (cross-site request forgery)
GitHub: https://github.com/axios/axios
Chinese document: http://www.axios-js.com/
7.2.Why use Axios
Because Vue.js is a view layer framework and the author (you Yuxi) strictly adheres to SoC (the principle of separation of concerns), Vue.js does not include the communication function of AJAX. In order to solve the communication problem, the author developed a plug-in called vue-resource, but stopped the maintenance of the plug-in and recommended the Axios framework after entering version 2.0. Use less jQuery because it manipulates Doms too often!
7.3.The first Axios application
Most of the interfaces we developed are in JSON format. You can first simulate a piece of JSON data in the project. The data content is as follows: create a file named data.json, fill in the above contents, and put it in the root directory of the project.
{"name": "crazy god says Java", "url": "https://blog.kuangstudy.com"," page ": 1," isNonProfit ": true," address ": {" street ":" light gate "," city ":" Xi'an, Shaanxi "," country ":" China "}," links ": [{" name ":" bilibili " "url": "https://space.bilibili.com/95256449"}, {" name ":" Java "," url ":" https://blog.kuangstudy.com"}, {"name": "Baidu", "url": "https://www.baidu.com/"}]}
Test code
Title [v-cloak] {display: none;}
Place name: {{info.name}}
Address: {{info.address.country}}-- {{info.address.city}}-- {{info.address.street}}
Link: {{info.url}}
Var vm = new Vue ({el: "# vue", / / data: attribute: vm data () {return {info: {name:null, address: {country:null, city:null Street:null}, url:null}, mounted () {/ / hook function axios. Get ('data.json'). Then (response= > (this.info=response.data)) })
Description:
Here, v-bind is used to bind the property values of a:href to the data in the Vue instance
Use the get method of the axios framework to request AJAX and automatically encapsulate the data in the data object of the Vue instance
Our data structure in data must match the format of the data returned by the Ajax response!
7.4. The life cycle of Vue
Official documentation: https://cn.vuejs.org/v2/guide/instance.html# lifecycle diagram
Vue instances have a complete lifecycle, that is, a series of processes, such as creating virgin data, compiling templates, mounting DOM, rendering updates, unloading, and so on. We call this the lifecycle of Vue. In popular terms, the process from creation to destruction of Vue instances is the life cycle.
Throughout the life cycle of Vue, provides a series of events that allow us to register JS methods when events are triggered, and to control the overall situation with our registered JS methods. The this in these event response methods points directly to the instance of Vue.
Computing attributes, content distribution, custom events 1, what are computational attributes
The focus of the calculation attribute is on the attribute (the attribute is a noun). First, it is an attribute. Secondly, this attribute has the ability to calculate (calculation is a verb). The calculation here is a function: to put it simply, it is an attribute that caches the results of the calculation (translates the behavior into a static attribute), and that's all; think of it as a cache!
Code on
Title
CurrentTime1: {{currentTime1 ()}}
CurrentTime2: {{currentTime2}}
Var vm = new Vue ({el: "# app", data: {message: "pan"}, methods: {currentTime1:function () {return Date.now () / / return a timestamp}}, computed: {currentTime2:function () {/ / Compute attribute: the methods,computed method name cannot be duplicated. After the same name, only the methods method this.message; return Date.now (); / / returns a timestamp})
Note: things in methods and computed cannot be renamed.
Description:
Methods: define the method, call the method using currentTime1 (), and need parentheses
Computed: define calculation properties, call properties using currentTime2, without parentheses: this.message is to allow currentTime2 to observe data changes
How the value in the method changes, the cache will be refreshed! You can use vm.message= "q in jiang" in the console to change the value of the data and test the observation effect again!
Conclusion:
When calls a method, it needs to talk about line computation every time. Since there is a computing process, it is bound to incur system overhead. What if the result does not change frequently? At this point, we can consider caching this result, which can be easily done by using calculation properties. The main characteristic of calculation attributes is to cache the calculation results that do not change frequently, so as to save our system overhead.
8.2. Content distribution
In Vue.js, we use elements as outlets for distribution, which the authors call slots, which can be used in composite component scenarios.
test
For example, you are going to make a to-do component (todo), which consists of a to-do title (todo-title) and to-do content (todo-items), but these three components are independent of each other.
The first step of is to define the components of a to-do list
Vue.component ('todo', {template:'
\
Agency matters
\\ learning maniac says Java\\
'})
In the second step, we need to dynamically bind the title and value of the to-do item. What should we do? We can save a slot!
1-leave the above code in a slot, slot
Vue.component ('todo', {template:'
\\
'})
2-define a to-do title component named todo-title and a to-do content component for todo-items
Vue.component ('todo-title', {props: [' title'], template:'
{{title}}
12345 index / here is the subscript of the array, which can be looped out when iterating through the for loop! Vue.component ("todo-items", {props: ["item", "index"], template: "{{index+1}}, {{item}"})
3-instantiate Vue and initialize data
Var vm = new Vue ({el: "# vue", data: {todoItems: ['test1','test2','test3']}})
4-insert these values through the slot
{if (valid) {/ / uses vue-router to route to the specified interface, which is called programmatic navigation this.$router.push ('/ main');} else {this.dialogVisible=true; return false;}) Login-box {border:1px solid # DCDFE6; width: 350px; margin:180px auto; padding: 35px 35px 15px 35px; border-radius: 5px;-webkit-border-radius: 5px;-moz-border-radius: 5px; box-shadow: 0 25px # 909399;}. Login-title {text-align:center; margin: 0 auto 40px auto; color: # 303133;}
Create a route and create a vue-router routing profile named index.js in the router directory
/ / Import vueimport Vue from 'vue';import VueRouter from' vue-router';// import component import Main from ".. / views/Main"; import Login from ".. / views/Login"; / / use Vue.use (VueRouter) / / Export export default new VueRouter ({routes: [{/ / login page path:'/ main', component: Main}, / / homepage {path:'/ login', component: Login},]})
APP.vue
Export default {name: 'App',} # app {font-family:' Avenir', Helvetica, Arial, sans-serif;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale; text-align: center; color: # 2c3e50; margin-top: 60px;}
Main.js
/ / The Vue build version to load with the `import`command// (runtime-only or standalone) has been set in webpack.base.conf with an alias.import Vue from 'vue'import App from'. / App'import router from ". / router" import ElementUI from 'element-ui'import' element-ui/lib/theme-chalk/index.css'Vue.use (router) Vue.use (ElementUI) / * eslint-disable no-new * / new Vue ({el:'# app', router, render:h= > h (App)})
Test: open http://localhost:8080/#/login in a browser
If an error occurs: it may be due to a compilation error caused by a higher version of sass-loader. The current maximum version is 8.0.2, which needs to be returned to 7.3.1.
Go to the package.json file and change the version of "sass-loader" to 7.3.1, and then re-cnpm install it.
12.3. Routing nesting
Nested routing, also known as sub-routing, is usually composed of multi-layer nested components in practical applications.
Demo
1. Create a user information component and create a view component called Profile.vue under the views/user directory
Profile.vue
Personal Information export default {name: "UserProfile"}
2. In the user list component, create a view component called List.vue in the views/user directory
List.vue
User list export default {name: "UserList"}
3. Modify the home view. We modify the Main.vue view component, where the ElementUI layout container component is used. The code is as follows:
Main.vue
User management personal information user list content management Classified management content list personal information login
Export default {name: "Main"}. El-header {background-color: # B3C0D1; color: # 333; line-height: 60px;} .el-aside {color: # 333;}
4. Configure nested routing to modify the index.js routing configuration file under the router directory, and use children to put the sub-module into main. The code is as follows
Index.js
/ / Import vueimport Vue from 'vue';import VueRouter from' vue-router';// import component import Main from ".. / views/Main"; import Login from ".. / views/Login"; / / Import submodule import UserList from ".. / views/user/List"; import UserProfile from ".. / views/user/Profile"; / / use Vue.use (VueRouter) / / Export export default new VueRouter ({routes: [{/ / login page path:'/ main', component: Main, / / write sub-module children: [{path:'/ user/profile', component: UserProfile,}, {path:'/ user/list', component: UserList,} ]}, / / homepage {path:'/ login', component: Login},]})
5. Routing nesting actual combat effect diagram
Graph routing nesting effect graph
12.4. Parameter transfer
This demonstrates how to pass a request with parameters.
Demo
uses the same code from the above example to modify some of the code. There is no repetitive code here.
The first way to take a value
1. Modify the routing configuration, mainly by adding a placeholder such as id to the path attribute in index.js under router.
{path:'/ user/profile/:id', name:'UserProfile', component: UserProfile}
2. Transfer parameters
at this time, we changed the to to: to at the route-link location in Main.vue, in order to use this attribute as an object. Note that the name attribute name in router-link must match the name attribute name in the route, because only in this way can Vue find the corresponding routing path.
Personal information
3. Use {{$route.params.id}} to receive the parameters in the component Profile.vue to be shown
Profile.vue partial code
Personal Information {{$route.params.id}}
The second value method uses props to reduce coupling.
1. Modify the routing configuration by adding the props: true attribute to the routing attribute in index.js under router.
{path:'/ user/profile/:id', name:'UserProfile', component: UserProfile, props: true}
2. Change the route-link address in Main.vue as before.
Personal information
3. Add the props attribute to the target component in the Profile.vue receive parameter
Profile.vue
Personal Information {{id}}
Export default {props: ['id'], name: "UserProfile"}
Picture transfer parameter effect picture
12.5. Component redirection
Everyone knows the meaning of redirection, but redirection in Vue works when the path is different but the components are the same, such as:
The configuration of index.js under router
{path:'/ main', name: 'Main', component: Main}, {path:' / goHome', redirect:'/ main'}
Description: two paths are defined here, one is / main, the other is / goHome, in which / goHome is redirected to the / main path, so you can see that redirection does not need to define components.
If you use it, you only need to set the corresponding path in Main.vue
Go back to home page 12.6, route patterns and 404
There are two route patterns
Hash: path with a # symbol, such as http://localhost/#/login
History: path without a # symbol, such as http://localhost/login
Modify the routing configuration as follows:
Export default new Router ({mode: 'history', routes: []})
404 demo
1. Create a NotFound.vue view component
NotFound.vue
404, your page is lost.
Export default {name: "NotFound"}
two。 Modify routing configuration index.js
Import NotFound from'.. / views/NotFound' {path:'*', component: NotFound}
3. Effect picture
Figure 404 effect diagram
Routing hooks and asynchronous requests
BeforeRouteEnter: execute before entering the route
BeforeRouteLeave: execute before leaving the rout
Write in Profile.vue
Export default {name: "UserProfile", beforeRouteEnter: (to, from, next) = > {console.log ("ready to enter personal information page"); next ();}, beforeRouteLeave: (to, from, next) = > {console.log ("ready to leave personal information page"); next ();}}
Parameter description:
To: the path information of the route to be redirected
From: path information before path jump
Next: control parameter for routin
Next () jumps to the next page
Next ('/ path') changes the direction of the route to jump to another route
Next (false) returns the original page
Next ((vm) = > {}) is only available in beforeRouteEnter, where vm is the component instance
Using asynchronous requests in hook functions
1. Install Axios
Cnpm install-save vue-axios
2. Main.js quotes Axios
Import axios from 'axios'import VueAxios from' vue-axios'Vue.use (VueAxios, axios)
3. Prepare the data: only the files in our static directory are accessible, so we put the static files in that directory.
The data is the same as the json data used before. Go to the axios example above.
/ / static/mock/data.json where static data is stored
4. Make asynchronous requests in beforeRouteEnter
Profile.vue
Export default {/ / second value method / / props: ['id'], name: "UserProfile", / / hook function filter beforeRouteEnter: (to, from, next) = > {/ / load data console.log ("before entering the route") next (vm = > {/ / execute the getData method vm.getData ()} before entering the route) }, beforeRouteLeave: (to, from, next) = > {console.log (before leaving the route) next () }, / / axios methods: {getData: function () {this.axios ({method: 'get', url:' http://localhost:8080/static/mock/data.json'}). Then (function (response) {console.log (response)})}
5. Routing Hook and axios combination Diagram
The above is all the contents of the article "what are the knowledge points of vue". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
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.