Mad God said Vue Notes

Mad God said Vue Notes

Mad God said Vue Notes

Video Search: Bilibili Mad God Talks about Java

​ There is still a long way to go to become a real "Internet Java full-stack engineer", and the front-end is a compulsory course that cannot be avoided. The main purpose of the course at this stage is to lead Java background programmers to know the front-end, understand the front-end, and master the front-end, and take another step forward to become an "Internet Java full-stack engineer".

1. Front-end core analysis

1.1. Overview

Soc Principle: Separation of Concerns

Vue's core library only focuses on the view layer, which is convenient for integration with third-party libraries or existing projects.

HTML + CSS + JS : View:给用户看,刷新后台给的数据

Network communication: axios

Page jump: vue-router

State management: vuex

Vue-UI: ICE , Element UI

1.2. Three front-end elements

  • HTML (structure): Hyper Text Markup Language (Hyper Text Markup Language), determines the structure and content of web pages
  • CSS (performance): Cascading Style Sheets (Cascading Style Sheets), set the presentation style of the web page.
  • JavaScript (behavior): It is a weakly typed scripting language. Its 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. Structure layer (HTML)

too simple

1.4. Presentation layer (CSS)

CSS Cascading Style Sheet is a markup language, not a programming language, so you cannot customize variables, quotes, etc. In other words, it does not have any grammatical support. Its main defects are as follows:

  • The syntax is not strong enough, for example, it cannot be nested and written, resulting in the need to write a lot of repeated selectors in modular development;
  • There is no variable and reasonable style reuse mechanism, so logically related attribute values ​​must be repeatedly output in literal form, making it difficult to maintain; this has led to a lot of unreasonable
    workload in our work. In order to solve this problem, front-end developers will use a tool called [CSS preprocessor] to provide a style layer reuse mechanism that CSS lacks, reduce redundant code, and improve the maintainability of style code. Greatly improved the development efficiency of the front-end style.

What is a CSS Preprocessor

The CSS preprocessor defines a new language. The basic idea is to use a special programming language to add some programming features to CSS, use CSS as the target to generate files, and then developers only need to use this language to do the coding work of CSS. To translate it into easy-to-understand words means " use a special programming language to design the Web page style, and then convert it into a normal CSS file through a compiler for project use. "

What are the commonly used CSS preprocessors?

  • SASS: Based on Ruby, it is processed through the server and has powerful functions. High analysis efficiency. You need to learn the Ruby language, which is more difficult than LESS.
  • LESS: Based on NodeJS, processed by the client, easy to use. The function is simpler than SASS, and the parsing efficiency is lower than SASS, but it is enough in actual development, so if our background staff needs it, it is recommended to use LESS.

1.5. Behavior layer (JavaScript)

JavaScript is a weakly typed scripting language. Its source code does not need to be compiled before it is sent to the client to run. 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 us follow the [ECMAScript] standard development method, referred to as ES, which is characterized by all browsers supporting it. As of now, the ES standard has released the following versions:

  • ES3
  • ES4 (internal, not officially released)
  • ES5 (full browser support)
  • ES6 (commonly used, the current mainstream version: webpack packaged into ES5 support)
  • ES7
  • ES8
  • ES9 (draft stage)

The difference is adding new features incrementally.
TypeScript Microsoft's standard
TypeScript is a free and open source programming language developed by Microsoft. It's a superset of JavaScript, and essentially adds optional static typing and class-based object-oriented programming to the language. Led by Anders Helsberger (father of C#, Delphi, TypeScript; creator of .NET). The feature of this language is that in addition to the features of ES, it also incorporates many new features that are not within the scope of the standard, so many browsers cannot directly support the TypeScript syntax, and it needs to be compiled (compiled into JS) to be correctly executed by the browser. .

JavaScript framework

  • JQuery: A well-known JavaScript library, the advantage is that it simplifies the DOM operation, and the disadvantage is that the DOM operation is too frequent, which affects the performance of the front-end; it is only used in the eyes of the front-end to be compatible with IE6, 7, 8;
  • Angular: The front-end framework acquired by Google was developed by a group of Java programmers. It is characterized by moving the back-end MVC model to the front-end and adding the concept of modular development . It cooperates with Microsoft and adopts TypeScript syntax development; it is friendly to back-end programmers , is not very friendly to front-end programmers; the biggest disadvantage is that the version iteration is unreasonable (such as 1st generation –> 2nd generation, except for the name, it is basically two things; Angular6 has been launched by the time of publishing the blog)
  • React: Produced by Facebook, a high-performance JS front-end framework; the feature is that a new concept [virtual DOM] is proposed to reduce real DOM operations, simulate DOM operations in memory, and effectively improve front-end rendering efficiency; the disadvantage is that it is complicated to use , because it is necessary to learn an additional [JSX] language;
  • Vue: A progressive JavaScript framework. The so-called progressive means to gradually implement new features, such as implementing new features such as modular development, routing, and state management. It is characterized by combining the advantages of Angular (modularization) and React (virtual DOM);
  • Axios: front-end communication framework; because the boundary of Vue is very clear, it is for processing DOM, so it does not have communication capabilities, and an additional communication framework is needed to interact with the server; of course, you can also directly choose to use the AJAX communication function provided by jQuery ;

2. Front-end development history

2.1. UI framework

  • Ant-Design: Produced by Alibaba, a UI framework based on React
  • ElementUI, iview, ice: Produced by Ele.me, Vue-based UI framework
  • BootStrap: An open source toolkit for front-end development by Teitter
  • AmazeUI: also known as "Sister UI", an HTML5 cross-screen front-end framework

2.2. JavaScript build tools

  • Babel: JS compilation tool, mainly used for ES new features not supported by browsers, such as compiling TypeScript
  • WebPack: module packager, the main function is to package, compress, merge and load in order

Note: The above knowledge points have sorted out all the skills required for WebApp development

2.3, three ends identical

Hybrid Development (Hybrid App)

The main purpose is to unify a set of codes at three terminals (PC, Android: .apk, iOS: .ipa) and be able to call the underlying hardware of the device (such as: sensor, GPS, camera, etc.). There are mainly two packaging methods:

  • Cloud packaging: HBuild -> HBuildX, produced by DCloud; API Cloud
  • Native packaging: Cordova (formerly PhoneGap)

WeChat applet

For details, please refer to the official website of WeChat. Here is a framework for UI development of WeChat applets: WeUI

2.4. Back-end technology

Front-end personnel also need to master certain back-end technologies for the convenience of development, but we Java background personnel know that the background knowledge system is extremely large and complex, so in order to facilitate front-end personnel to develop background applications, technologies such as Node JS have emerged. The author of Node JS has already claimed to abandon Node JS (it is said that the architecture is not well done and the cumbersome node modules may make the author unhappy) and started to develop a new architecture. De no Since it is a background technology, it must also require a framework
and Project management tools, Node JS framework and project management tools are as follows:

  • Express: A Node JS framework
  • Koa: Express Lite
  • NPM: project comprehensive management tool, similar to Maven
  • YARN: An alternative to NPM, similar to the relationship between Maven and Gradle

2.5. Mainstream front-end framework

Vue.js

View

iview is a powerful Vue-based UI library. It has many practical basic components that are richer than element ui components. It mainly serves the middle and background products of the PC interface. The single-file Vue component development model is developed based on npm+webpack+babel, supports ES 2015's high-quality, feature-rich and friendly API, and uses space freely and flexibly.

  • Official website address
  • Github
  • iview-admin

Remarks: It belongs to the front-end mainstream framework and can be considered when selecting models. The main feature is that it supports more mobile terminals

Element UI

Element is a Vue UI component library maintained by Ele.me's front-end open source. It has complete components and basically covers all the components needed in the background. The documentation explains in detail and there are many examples. Mainly used to develop PC-side pages, it is a relatively high-quality Vue UI component library.
·Official website address
·Git hub
·vue-element-admin
Remarks: It belongs to the front-end mainstream framework, which can be considered when selecting models. The main feature is that it supports more desktops

ICE

Flying Ice is a React/Angular/Vue-based mid-background application solution of the Alibaba team. Within Alibaba, there are already more than 270 projects from almost all BUs in use. Feibing includes a complete link from the design end to the development end, helping users quickly build their own middle and back-end applications.

  • Official website address.

  • Git hub

Remarks: The main components are still based on React. As of February 17, 2019, the support for Vue is not perfect before the blog is updated, and it is still in the wait-and-see stage

VantUI

Vant UI is a Vue component library implemented by Youzan's front-end team based on Youzan's unified specifications, providing a complete set of UI basic components and business components. Through Vant, you can quickly build pages with a unified style and improve development efficiency.

  • Official website address
  • Github

AtUI

at-ui is a front-end UI component library based on Vue 2.x, mainly used for rapid development of PC website products. It provides a set of n pm+web pack+babel front-end development workflow, independent CSS styles, and can maintain a unified UI style even if different frameworks are used for implementation.
·Official website address
·Git hub

Cube Ul

cube-ui is an exquisite mobile component library based on Vue js developed by Didi team. Support on-demand introduction and post-compilation, lightweight and flexible; strong scalability, 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 period of time. Flutter works with existing code, it is used by developers and organizations all over 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 hybrid applications, this framework is a mandatory framework

lonic

Ionic is both a CSS framework and a Javascript UI library. Ionic is currently the most promising HTML 5 mobile application development framework. Build applications through SASS, which provides many UI components to help developers develop powerful applications. It uses JavaScript MV VM framework and Angular JS/Vue to enhance the application. Provides two-way binding of data, making it a common choice for web and mobile developers.

  • Official website address

·Official Documentation
·Git hub

WeChat applet

mpue

mpvue is a front-end framework developed by Meituan for using and Vue.jsdeveloping mini-programs. It currently supports WeChat mini-programs, Baidu smart mini-programs, Toutiao mini-programs and Alipay mini-programs. The framework is based on Vue.jsthe modified runtime framework runtimeand code compiler compilerimplementation, so that it can run in the applet environment, thus introducing a Vue.jsdevelopment experience for applet development.
·Official website address
·Git hub
note: complete Vue development experience, and supports multi-platform small program development, recommended to use

WebUI

WeUI is a set of basic style libraries that are consistent with the original visual experience of WeChat. It is designed by WeChat's official design team for WeChat web pages and WeChat applets, making users' usage perception more unified. Contains various elements such as button, cell, dialog, toast, article, icon, etc.

  • Official website address
  • Github

3. Understand the evolution history of front-back separation

Why do you need front and rear separation

3.1. Back-end-based MVC era

In order to reduce the complexity of development, the starting point is the backend. For example, the use of frameworks such as Struts and Spring MVC is the MVC era of the backend; take the process as an
example SpringMVC:
insert image description here

  • Initiate a request to the front controller ( Dispatcher Servlet)
  • The front controller requests HandlerMappingto search Handler, which can xmlbe searched according to configuration and annotations
  • The processor mapper HandlerMappingreturns to the front controllerHandler
  • The front controller calls the handler adapter to executeHandler
  • processor adapter to executeHandler
  • HandlerExecution is complete and returns to the adapterModelAndView
  • The processor adapter returns to the front controller ModelAndViewand ModelAndViewis SpringMvca low-level object of the framework, including ModelandView
  • The front controller requests the view resolver to resolve the view, and resolves it into a real view according to the logical view name ( JSP)
  • The view resolver returns to the front controllerView
  • Front controller does view rendering which populates fields with model data (in objects ModelAndView)request
  • The front-end controller responds to the results of the user.
    Advantages
    MVC is a very good collaboration model, which can effectively reduce the coupling of the code. From the architecture, it allows developers to understand where the code should be written. In order to make the View more pure, template engines such as Thyme leaf and Frree marker can also be used, so that Java code cannot be written in the template, and the division of labor between the front and back ends is clearer.
    shortcoming
  • Front-end development relies heavily on the development environment, and the development efficiency is low. Under this architecture, there are two modes of front-end and back-end collaboration:
    • The first is to write the DEMO on the front end, and let the back end set the template after writing it. The advantage is that DEMO can be developed locally, which is very efficient. The disadvantage is that the template needs to be set at the back end, and it may be set wrongly. After the set is completed, the front end needs to be confirmed, and the cost of back and forth communication and adjustment is relatively large;
    • Another collaboration mode is that the front end is responsible for all development on the browser side and the development of View layer templates on the server side. The advantage is that all UI-related codes should be written by the front-end, and the back-end does not need to pay too much attention. The disadvantage is that the front-end development is heavily bound to the back-end environment, and the environment becomes an important factor affecting the efficiency of front-end development.
  • The front-end and back-end responsibilities are entangled: the template engine is powerful, and it can still implement various business logics through the obtained context variables. In this way, as long as the front-end is weaker, it is often required by the back-end to write a lot of business code in the template layer. There is also a big gray area in the Controller. Functions such as page routing should be the most concerned by the front-end, but it is implemented by the backend. The Controller itself and the Model are often entangled, and the business code that makes people bite their teeth often appears in the Controller layer. These problems cannot all be attributed to the quality of programmers, otherwise JSP is enough.
  • Limitations on the front-end: If performance optimization is only done on the front-end, the space 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 early JSP, PHP can be called the Web 1.0 era. I would like to say something here, if you are a beginner in Java, please stop taking some old technologies seriously, such as JSP, because times are changing, technologies are changing, and everything is changing (quote Zuckerberg A sentence from Gege: the only constant is change itself); when we go to the university to do practical training, some students will think that we have not talked about dry goods, but it is not the case. It can only be said that the dry goods in your cognition are for the market. It's too late to say

3.2. The era of SPA based on AJAX

Back in 2005, A OAX (Asynchronous JavaScript And XML, asynchronous JavaScript and XML, old technology and new usage) was officially proposed and began to use CDN as static resource storage, so the return of the JavaScript king appeared (before this, JS was used to The era of SPA (Single Page Application) where dog skin plaster advertisements are posted on the web page.
insert image description here
Advantages
In this mode, **The division of labor between the front and back ends is very clear, and the key collaboration point between the front and back ends is the AJAX interface. **It looks so good, but looking back, it's not that different from the JSP era. The complexity has moved from JSP on the server side to JavaScript on the browser, and the browser side has become very complicated. Similar to Spring MVC, a layered architecture on the browser side began to appear in this era :
insert image description here
Disadvantages

  • Agreement on front-end and back-end interfaces : If the back-end interface is in a mess, and if the back-end business model is not stable enough, then front-end development will be very painful; many teams have made similar attempts to do so through interface rules and interface platforms. With the interface rules precipitated together with the backend, it can also be used to simulate data, so that the frontend and backend can achieve efficient parallel development after agreeing on the interface.
  • Complexity control of front-end development: Most SPA applications are functionally interactive, and it is normal for JavaScript code to exceed 100,000 lines. The organization of a large amount of JS code, the binding with the View layer, etc. are not easy tasks.

3.3. Front-end-oriented MV* Era

The MV* schema here is as follows:

  • MVC (mainly synchronous communication): Model, View, Controller
  • MVP (mainly asynchronous communication): Model, View, Presenter
  • MVVM (mainly asynchronous communication): Model, View, and View Model In order to reduce the complexity of front-end development, a large number of front-end frameworks have emerged, such as: , , , etc. The general principle of these frameworks Angular JSis Reactto Vue.jsfirst Ember JSlayer by type, such as Templates, Controllers, Models, and then do segmentation within the layer, as shown below:

insert image description here

advantage

  • The front-end and back-end responsibilities are very clear : the front-end works on the browser side, and the back-end works on the server side. A clear division of labor allows parallel development, easy simulation of test data, and local development of the front end. The backend can focus on the processing of business logic and output RESTful interfaces.
  • The complexity of front-end development is controllable : the front-end code is heavy, but the reasonable layering allows the front-end code to perform its duties. This one is quite interesting, as simple as the selection of template features, there are many, many things to pay attention to. The more powerful the better, what is restricted, what freedom is left, how the code should be organized, all of these designs need to be explained in the thickness of a book.
  • Deployment is relatively independent : product experience can be quickly improved Disadvantages
  • Code cannot be reused. For example, the backend still needs to perform various verifications on the data, and the verification logic cannot reuse the browser-side code. If it can be reused, the data verification at the back end can be relatively simple.
  • All asynchronous, not good for SEO. It is often necessary for the server to perform a degradation solution for synchronous rendering.
  • The performance is not optimal, especially in the mobile Internet environment.
  • SPA cannot meet all needs, and there are still a large number of multi-page applications. URL Design requires the cooperation of the backend, and the frontend cannot fully control it.

3.4. The full-stack era brought by Node JS

The front-end-based MV* model has solved many, many problems, but as mentioned above, there are still many deficiencies. With the rise of Node JS, JavaScript has the ability to run on the server side. This means that there can be a new research and development model:
insert image description here
in this research and development model, the responsibilities of the front and back ends are very clear. For the front end, the two UI layers perform their duties:

  • The Front-end Ul layer handles the presentation logic of the browser layer. Styles are rendered through CSS, interactive functions are added through JavaScript, and HTML generation can also be placed on this layer, depending on the application scenario.
  • Back-end Ul layer handles routing, templates, data acquisition, cookies, etc. 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 freely control it. The backend can finally get rid of the strong focus on presentation, and can instead concentrate 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 back and forth. Scenes requiring SEO can be rendered synchronously on the server side, and performance problems caused by too many asynchronous requests can also be alleviated through the server side. The deficiencies of the previous model can almost be perfectly solved by this model.
    Compared with the JSP mode, the full-stack mode seems to be a regression, and it is indeed a regression to the original development mode, but it is a spiral regression.
    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. For example, the mastery of network knowledge such as TCP/IP.
  • Efficient communication between Node JS layer and Java layer. In Node JS mode, all are on the server side, RESTful HTTP communication may not be efficient, and communication through SOAP and other methods is more efficient. Everything needs to go forward in verification.
  • A proficient understanding of department and operation and maintenance requires more knowledge points and practical experience.
  • How to transition a large number of historical issues. This is probably the greatest and greatest resistance.
    Note: Seeing this, I believe many students can understand why I always say in class: "It is difficult for the front-end to learn the background, but it is easy for us back-end programmers to learn anything"; it is because of our back-end programmers Have a relatively complete knowledge system.
    Full stack! So Easy!

3.5. Summary

To sum up, no matter whether it is a model or a technology, there is no distinction between good and bad, only suitable or not; the development idea of ​​separation of front and back is mainly based on (the Socprinciple of separation of attention), and all the above models are the responsibility of the front and back ends Clearer, more reasonable and efficient division of labor.

4. The first Vue program

4.1, what is MVVM

MVVM (Model-View-ViewModel) is a software design pattern composed of Microsoft WPF (used to replace WinForm, which was used to develop desktop applications in the past) and Silverlight (similar to Java Applet, simply put, in the browser Developed by architects Ken Cooper and Ted Peters on WPF), it is an event-driven programming method that simplifies the user interface . Published by John Gossman (also architect of WPF and Silverlight) on his blog in 2005.

MVVM is derived from the classic MVC (Model-View-Controller) pattern. The core of MVVM is the ViewModel layer, which is responsible for transforming the data objects in the Model to make the data easier to manage and use. Its role is as follows:

  • This layer goes up to the view layer for two-way data binding
  • Data interaction with the Model layer through interface requests

insert image description here

MVVM is quite mature and is mainly used but not only in web application development. The current popular MVVM frameworks are Vue.js,Anfular JS

4.2. Why use MVVM

The MVVM pattern is the same as the MVC pattern. The main purpose is to separate the view (View) and the model (Model). There are several advantages

  • Low coupling : View (View) can be changed and modified independently of Model. A ViewModel can be bound to different Views. When the View changes, the Model can remain unchanged, and when the Model changes, the View can also remain unchanged.
  • Reusable : You can put some view logic in a ViewModel and let many Views reuse this view logic.
  • Independent development : developers can focus on business logic and data development (ViewMode), and designers can focus on page design.
  • Testable : Interfaces have always been difficult to test, but now tests can be written for ViewModel.
insert image description here

(1)View

View is the view layer, which is the user interface. The front-end is mainly constructed by HTH L and csS. In order to display the data of vi eu to del or Hodel layer more conveniently, various front-end and back-end template languages ​​have been produced, such as FreeMarker, Thyme leaf, etc., and major MV VMs Frameworks such as Vue.js, Angular JS, EJS, etc. also have their own built-in templating languages ​​for building user interfaces.

(2)Model

Model refers to the data model, which generally refers to various business logic processing and data manipulation performed by the backend, and mainly revolves around the database system. The difficulty here mainly lies in the need to agree on a unified interface rule with the front end

(3)ViewModel

ViewModel is a view data layer generated and maintained by an organization of front-end developers. At this layer, the front-end developers convert and process the Model data obtained from the back-end, and perform secondary packaging to generate a view data model that meets the expectations of the View layer.
  It should be noted that the data model encapsulated by the View Model includes two parts: the state and the behavior of the view, while the data model of the Model layer only includes the state

  • For example, what is displayed on this part of the page, and what is displayed on that part, these all belong to the view state (display)
  • What happens when the page is loaded, what happens when you click on this piece, and what happens when this piece scrolls. These all belong to the view behavior (interaction)

View state and behavior are encapsulated in the View Model. Such encapsulation enables the View Model to completely describe the View layer. Due to the realization of two-way binding, the content of the View Model will be displayed in the View layer in real time, which is exciting, because front-end developers no longer have to update the view by manipulating the DOM inefficiently and troublesomely.
  The MVVM framework has already done the dirtiest and most tiring part. Our developers only need to process and maintain the View Model, and updating the data view will automatically be updated accordingly, which is truly realized 事件驱动编程.
  What the View layer displays is not Modelthe data of the layer, but ViewModelthe data of the layer. It is responsible for interacting ViewModelwith the layer, which completely decouples the View layer and the Model layer. This decoupling is crucial, and it is an important part of the implementation of the separation scheme one ring.Model

4.3、Vue

Vue (pronounced /vju/, similar to view) is a progressive framework for building user interfaces, 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 pattern

  • Model: Model layer, where JavaScript objects are represented
  • View: The view layer, where DOM (element of HTML operation) is represented
  • ViewModel: middleware that connects views and data, Vue.js is the implementer of the View Model layer in MVVM

In the MVVM architecture, data and views are not allowed to communicate directly, only through ViewModel, and View Model defines an Observer observer

  • ViewModel can observe data changes and update the content corresponding to the view
  • ViewModel can listen to changes in the view and can notify the data of changes

So far, we understand that Vue.js is an implementer of MV VM, and its core is to realize DOM monitoring and data binding

(2) Why use Vue.js

  • Lightweight, small size is an important indicator. Vue.js is only more than 20kb after compression (56kb+ after Angular compression, 44kb+ after React compression)
  • Mobile first. More suitable for mobile terminals, such as touch events on mobile terminals
  • Easy to use, smooth learning curve, complete documentation
  • It absorbs the strengths of Angular (modularization) and React (virtual DOM), and has its own unique features, such as: computed properties
  • Open source, highly active community

4.4. The first Vue program

[Description] IDEA can install Vue plug-ins!
  Note: Vue does not support IE 8 and below, because Vue uses ECMAScript 5 features that IE 8 cannot emulate. But it supports all ECMAScript 5 compliant browsers.

(1) Download address

  • development version
    • Contains full warning and debug mode: https://yuejs.org/js/vue.js
    • Removed warning, 30.96KB min+gzip: https://vuejs.org/js/vue.min.js
  • CDN

(2) Code writing

The core of Vue.js is to realize the MVVM mode. The role she plays is the View Model layer. Then the so-called first application is to display her data binding function. The operation process is as follows: 1. Create an HTML
  file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

</body>
</html>

2. Introduce Vue.js

<!--1.导入Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
12

3. Create a Vue instance

<script type="text/javascript">
    var vm = new Vue({
      
      
        el:"#app",
        /*Model:数据*/
        data:{
      
      
            message:"hello,vue!"
        }
    });
</script>

illustrate:

  • el: '#vue': ID of the bound element
  • data:{message:'Hello Vue!'}: There is an attribute named message in the data object, and the initial value Hello Vue!

4. Bind data to page elements

<!--view层,模板-->
<div id="app">
    {
   
   {message}}
</div>

Explanation: You only need to use double curly braces in the bound element to wrap the property named message created by Vue to realize the data binding function, and also realize the effect required by the View Model layer. Is it expressed with EL? very similar?

(3) Complete HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>

<!--view层,模板-->
<div id="app">
    {
   
   {message}}
</div>

<!--1.导入Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script type="text/javascript">
    var vm = new Vue({
      
      
        el:"#app",
        /*Model:数据*/
        data:{
      
      
            message:"hello,vue!"
        }
    });
</script>
</body>
</html>

(4) test

In order to experience the data binding function brought by Vue more intuitively, we need to test it in the browser. The operation process is as follows:
  1. Run the first Vue application on the browser, enter the developer tool
  2. In the control Enter vm.message='HelloWorld' on the console, and then press Enter, you will find that the content displayed in the browser will directly change to HelloWorld.
  At this time, you can directly enter vm.message in the console to modify the value, and the data can be omitted in the middle , In this operation, I did not actively manipulate the DOM, so that the content of the page changed, which was realized with the help of Vue's data binding function; the MV VM mode requires the View Model layer to be implemented using the observer mode Data monitoring and binding to achieve fast response to data and views.

5. Basic Grammatical Instructions

4.1、v-bind

We've successfully created our first Vue application! It looks like rendering a string template, but Vue is doing a lot of work behind the scenes. Now that the data and DOM are linked, everything is responsive. We operate object properties on the console, and the interface can be updated in real time!
  We can also use v-bind to bind element features!
  The above code

<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

</head>
<body>

<!--view层,模板-->
<div id="app">
    <span v-bind:title="message">
    鼠标悬停几秒钟查看此处动态绑定的提示信息!
  </span>
</div>

<!--1.导入Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script type="text/javascript">
    var vm = new Vue({
      
      
        el:"#app",
        /*Model:数据*/
        data:{
      
      
            message: '页面加载于 ' + new Date().toLocaleString()
        }
    });
</script>
</body>
</html>

The v-bind etc. you see are called directives. Directives are prefixed with v to indicate that they are special features provided by Vue. As you may have guessed, they apply special responsive behavior on the rendered DOM. Here, the directive means: "Make 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, enter app, message='new message', you will see that the HTML bound to the title feature has been updated again.

4.2、v-if, v-else

What is a conditional judgment statement, I don’t need to explain it, the following two attributes!

  • v-if
  • v-else

upper code

<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--view层,模板-->
<div id="app">
    <h1 v-if="ok">Yes</h1>
    <h1 v-else>No</h1>
   
</div>

<!--1.导入Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script type="text/javascript">
    var vm = new Vue({
      
      
        el:"#app",
        /*Model:数据*/
        data:{
      
      
            type: true
        }
    });
</script>
</body>
</html>

Test:
1. Run on the browser, open the console!
2. Enter in the console vm.ok=falseand press Enter, you will find that the content displayed in the browser will directly change to NO
  Note: Using v-*attributes to bind data does not require 双花括号wrapping

v-else-if

  • v-if
  • v-else-if
  • v-else
      Note: ===Three equal signs in JS means absolute equal (that is, the data and type must be equal) above code:
<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--view层,模板-->
<div id="app">
    <h1 v-if="type==='A'">A</h1>
    <h1 v-else-if="type==='B'">B</h1>
    <h1 v-else-if="type==='D'">D</h1>
    <h1 v-else>C</h1>

</div>

<!--1.导入Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script type="text/javascript">
    var vm = new Vue({
      
      
        el:"#app",
        /*Model:数据*/
        data:{
      
      
            type: 'A'
        }
    });
</script>
</body>
</html>

4.3、v-for

  • v-for

format description

<div id="app">
    <li v-for="(item,index) in items">
        {
   
   {item.message}}---{
   
   {index}}
    </li>

</div>
123456

Note: itemsIt is an array, itemwhich is an alias for iteration of array elements. The syntax of the Thymeleaf template engine we will learn later is very similar to this!
  Above code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--view层,模板-->
<div id="app">
    <li v-for="(item,index) in items">
        {
   
   {item.message}}---{
   
   {index}}
    </li>

</div>

<!--1.导入Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script type="text/javascript">
    var vm = new Vue({
      
      
        el:"#app",
        /*Model:数据*/
        data:{
      
      
            items:[
                {
      
      message:'狂神说Java'},
                {
      
      message:'狂神说前端'},
                {
      
      message:'狂神说运维'}
            ]
        }
    });
</script>
</body>
</html>

Test: Enter in the console vm.items.push({message:'狂神说运维'}), try to add a piece of data, and you will find that the content displayed in the browser will increase 狂神说运维.

4.4、v-on

v-onListen to the event
 emsp; events include Vue events and some events on the front-end page itself! We are here for clickvue events, which can be bound to methodsthe method events in Vue!
  The above code :

<!DOCTYPE html>
<html lang="en" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div id="app">
    <button v-on:click="sayHi">点我</button>
</div>

<script src="../js/vue.js"></script>
<script type="text/javascript">
    var vm = new Vue({
      
      
        el:"#app",
        data:{
      
      
            message:'Hello World'
        },
        methods:{
      
      
            sayHi:function(event){
      
      
                //'this'在方法里面指向当前Vue实例
                alert(this.message);
            }
        }
    });
</script>
</body>
</html>

Click to test
  Vue and some basic ways of using it. If you need it, you can follow the official document to see it, because we have seen almost all of these basic instructions, and they know everything! Master the way of learning!

Six, form double binding, components

6.1, what is two-way data binding

Vue.js is an MV VM framework, that is, two-way data binding, that is, when the data changes, the view also changes, and when the view changes, the data also changes synchronously. This is also the essence of Vue.js.
  It is worth noting that the two-way data binding we are talking about must mean that non-UI controls for UI controls will not involve two-way data binding. One-way data binding is a prerequisite for using state management tools. If we use vue x, the data flow is also single-item, which will conflict with two-way data binding.

(1) Why implement two-way binding of data

In Vue.js, if you use it vuex, the data is actually one-way. The reason why it is called two-way data binding is that it is used for UI controls. For us to process forms, the Vue.jstwo-way data binding is very comfortable to use. That is to say, the two are not mutually exclusive, and a single item is used in the global data flow to facilitate tracking; the local data flow uses two-way, which is simple and easy to operate.

6.2. Using two-way data binding in forms

You can use v-modeldirectives to create two-way data bindings on forms and elements. It automatically picks the correct method to update the element based on the control type. While magical, it v-model's essentially nothing more than syntactic sugar. It is responsible for listening to user input events to update data, and doing some special processing for some extreme scenarios.
  Note: The initial values ​​of , , and attributes v-modelof all form elements will be ignored and the data of the instance will always be used as the data source. You should declare the initial value in the component's options!valuecheckedselectedVueJavaScriptdata

(1) Single-line text

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">
    输入的文本:<input type="text" v-model="message" value="hello">{
   
   {message}}
</div>

<script src="../js/vue.js"></script>
<script type="text/javascript">
    var vm = new Vue({
      
      
        el:"#app",
        data:{
      
      
            message:""
        }
    });
</script>
</body>
</html>

(2) Multi-line text

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">
   多行文本:<textarea v-model="pan"></textarea>&nbsp;&nbsp;多行文本是:{
   
   {pan}}
</div>

<script src="../js/vue.js"></script>
<script type="text/javascript">
    var vm = new Vue({
      
      
        el:"#app",
        data:{
      
      
            message:"Hello hello!"
        }
    });
</script>
</body>
</html>

(3) Single check box

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div id="app">
    单复选框:
    <input type="checkbox" id="checkbox" v-model="checked">
    &nbsp;&nbsp;
    <label for="checkbox">{
   
   {checked}}</label>
</div>

<script src="../js/vue.js"></script>
<script type="text/javascript">
    var vm = new Vue({
      
      
        el:"#app",
        data:{
      
      
            checked:false
        }
    });
</script>
</body>
</html>

( 4 ) Multiple check boxes

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div id="app">
    多复选框:
    <input type="checkbox" id="jack" value="Jack" v-model="checkedNames">
    &nbsp;&nbsp;
    <label for="jack">Jack</label>
    <input type="checkbox" id="join" value="Join" v-model="checkedNames">
    &nbsp;&nbsp;
    <label for="join">Jack</label>
    <input type="checkbox" id="mike" value="Mike" v-model="checkedNames">
    &nbsp;&nbsp;
    <label for="mike">Mike</label>
    <span>选中的值:{
   
   {checkedNames}}</span>
</div>

<script src="../js/vue.js"></script>
<script type="text/javascript">
    var vm = new Vue({
      
      
        el:"#app",
        data:{
      
      
            checkedNames:[]
        }
    });
</script>
</body>
</html>

(6) Radio buttons

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div id="app">
    单选框按钮
    <input type="radio" id="one" value="One" v-model="picked">
    <label for="one">One</label>
    <input type="radio" id="two" value="Two" v-model="picked">
    <label for="two">Two</label>
    <span>选中的值:{
   
   {picked}}</span>
</div>

<script src="../js/vue.js"></script>
<script type="text/javascript">
    var vm = new Vue({
      
      
        el:"#app",
        data:{
      
      
            picked:'Two'
        }
    });
</script>
</body>
</html>

(7) Drop-down box

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">
<!--    性别:
    <input type="radio" name="sex" value="男" v-model="pan">男
    <input type="radio" name="sex" value="女" v-model="pan">女
    <p>选中了:{
    
    {pan}}</p>-->

    下拉框:
    <select v-model="pan">
        <option value="" disabled>---请选择---</option>
        <option>A</option>
        <option>B</option>
        <option>C</option>
        <option>D</option>
    </select>
    <span>value:{
   
   {pan}}</span>



</div>

<script src="../js/vue.js"></script>
<script type="text/javascript">
    var vm = new Vue({
      
      
        el:"#app",
        data:{
      
      
            pan:"A"
        }
    });
</script>
</body>
</html>

Note: v-modelThe initial value of the expression fails to match any options, and the element system will be rendered as "unselected". In iOS, this prevents the user from selecting the first option, because iOS does not fire the event in this case change. Therefore, it is more recommended to provide a disabled option with an empty value as above.

6.3, what is a component

Components are reusable Vueinstances. To put it bluntly, they are a set of reusable templates. They are similar to JSTLcustom tags and Thymelealother frameworks. Usually an application will be organized in the form of a nested component tree:th:fragment
insert image description here
insert image description here

For example, you might have components such as header, sidebar, content area, etc., each of which contains other components like navigation links, blog posts, etc.

(1) The first Vue component

Note: In actual development, we do not use the following methods to develop components, but to vue-clicreate and vuedevelop template files. The following methods are just for everyone to understand what a component is.
  Use Vue.component()the method to register the component, the format is as follows:

<div id="app">
  <pan></pan>
</div>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script type="text/javascript">
    //先注册组件
    Vue.component("pan",{
      
      
        
        template:'<li>Hello</li>'

    });
    //再实例化Vue
    var vm = new Vue({
      
      
        el:"#app",
    });
</script>

illustrate:

  • Vue.component(): register component
  • pan: the name of the custom component
  • template: template for the component

(2) Use propsattributes to pass parameters

It doesn't make any sense to use components like above, so we need to pass parameters to components, and we need to use propsattributes at this time!
  Note: under the default rules, the value in the props attribute cannot be uppercase;

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div id="app">
    <!--组件:传递给组件中的值:props-->
  <pan v-for="item in items" v-bind:panh="item"></pan>
</div>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script type="text/javascript">
    //定义组件
    Vue.component("pan",{
      
      
        props:['panh'],
        template:'<li>{
      
      {panh}}</li>'

    });
    var vm = new Vue({
      
      
        el:"#app",
        data:{
      
      
            items:["java","Linux","前端"]
        }
    });
</script>
</body>
</html>

Description :

  • v-for="item in items": Iterate through the array Vuenamed in the instance defined itemsand create an equal number of components
  • v-bind:panh="item": Bind the traversed item to the property defined itemin the component ; the left side of the = sign is the defined property name, and the right side is the value of the traversed item inpropsitempanhpropsitem in items

Seven, Axios asynchronous communication

7.1, what is Axios

Axios is an open source asynchronous communication framework that can be used in browsers and websites Node JS. Its main function is to realize AJAX asynchronous communication. Its features are as follows:

  • Created from the browserXMLHttpRequests
  • Create http request from node.js
  • Support Promise API [chain programming in JS]
  • Intercept requests and responses
  • Transform request data and response data
  • cancel request
  • Automatically convert JSON data
  • The client supports defense against XSRF (cross-site request forgery)

GitHub: https://github.com/axios/axios
  Chinese documentation: http://www.axios-js.com/

7.2. Why use Axios

Since Vue.jsit is a view layer framework and the author (You Yuxi) strictly abides by SoC (the principle of separation of concerns), it does Vue.jsnot include the AJAX communication function. In order to solve the communication problem, the author developed a vue-resourceplug-in called separately, but after entering After version 2.0, the maintenance of the plugin was stopped and Axiosthe framework was recommended. Use less jQuery, because it manipulates the Dom too frequently!

7.3. The first Axios application

Most of the interfaces we develop 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 and fill in the above content, and put it in the root directory of the project

{
    
    
  "name": "狂神说Java",
  "url": "https://blog.kuangstudy.com",
  "page": 1,
  "isNonProfit": true,
  "address": {
    
    
    "street": "含光门",
    "city": "陕西西安",
    "country": "中国"
  },
  "links": [
    {
    
    
      "name": "bilibili",
      "url": "https://space.bilibili.com/95256449"
    },
    {
    
    
      "name": "狂神说Java",
      "url": "https://blog.kuangstudy.com"
    },
    {
    
    
      "name": "百度",
      "url": "https://www.baidu.com/"
    }
  ]
}

test code

<!DOCTYPE html>
<html lang="en" xmlns:v-binf="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--v-cloak 解决闪烁问题-->
    <style>
        [v-cloak]{
      
      
            display: none;
        }
    </style>
</head>
<body>
<div id="vue">
    <div>地名:{
   
   {info.name}}</div>
    <div>地址:{
   
   {info.address.country}}--{
   
   {info.address.city}}--{
   
   {info.address.street}}</div>
    <div>链接:<a v-binf:href="info.url" target="_blank">{
   
   {info.url}}</a> </div>
</div>

<!--引入js文件-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/javascript">
    var vm = new Vue({
      
      
        el:"#vue",
        //data:属性:vm
        data(){
      
      
            return{
      
      
                info:{
      
      
                    name:null,
                    address:{
      
      
                        country:null,
                        city:null,
                        street:null
                    },
                    url:null
                }
            }
        },
        mounted(){
      
      //钩子函数
            axios
                .get('data.json')
                .then(response=>(this.info=response.data));
        }
    });
</script>
</body>
</html>

illustrate:

  1. Here, v-bind is used to bind the attribute value of a:href to the data in the Vue instance
  2. Use the get method of the axios framework to request AJAX and automatically encapsulate the data into the data object of the Vue instance
  3. Our data structure in data must Ajaxmatch the data format of the response!

7.4, the life cycle of Vue

Official document: https://cn.vuejs.org/v2/guide/instance.html#Life cycle diagram
  Vue instance has a complete life cycle, that is, from the beginning to create initialized data, compile templates, mount A series of processes such as DOM, rendering-update-rendering, unloading, etc., we call this the life cycle of Vue. In layman's terms, it is the process of a Vue instance from creation to destruction, which is the life cycle.
  Throughout the life cycle of Vue, it provides a series of events that allow us to register JS methods when events are triggered, allowing us to control the overall situation with our own registered JS methods. This in these event response methods directly points to is an instance of Vue.
insert image description here

8. Calculated properties, content distribution, custom events

1. What is a computed property

The focus of the calculation attribute is 属性two words (attribute is a noun), firstly it is a capability of属性 this attribute (calculation is a verb), here is a function: simply put, it is a function that can cache the calculation result Attributes (transforming behavior into static attributes), nothing more; it can be imagined as a cache! The above code计算计算
  

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--view层,模板-->
<div id="app">
    <p>currentTime1:{
   
   {currentTime1()}}</p>
    <p>currentTime2:{
   
   {currentTime2}}</p>
</div>

<!--1.导入Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script type="text/javascript">
    var vm = new Vue({
      
      
        el:"#app",
        data:{
      
      
          message:"pan"
        },
        methods:{
      
      
            currentTime1:function(){
      
      
                return Date.now();//返回一个时间戳
            }
        },
        computed:{
      
      
            currentTime2:function(){
      
      //计算属性:methods,computed方法名不能重名,重名之后,只会调用methods的方法
                this.message;
                return Date.now();//返回一个时间戳
            }
        }
    });
</script>
</body>
</html>

Note: the things in methods and computed cannot have the same name
Explanation:

  • methods: Define the method, call the method using currentTime1(), need to have parentheses

  • computed: define computed properties, use currentTime2 to call properties, do not need brackets: this.message is to allow currentTime2 to observe data changes

  • If the value in the method changes, the cache will be refreshed! It can be used in the console vm.message=”q in jiang", change the value of the data, and test the observation effect again!

    Conclusion:
      When calling a method, calculations are required every time. Since there is a calculation process, system overhead must be incurred. What if the result does not change frequently? At this point, you can consider caching the result. Using the calculation attribute can It is very convenient to do this. The main feature of the calculation attribute 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 <slot>elements as the outlet to carry and distribute content. The author calls them slots, which can be applied in the scene of combining components;

test

For example, we are going to make a todo component (todo), which is composed of todo title (todo-title) and todo content (todo-items), but these three components are independent of each other, how to operate?
  The first step is to define a to-do component

<div id="app">
    <todo></todo>
</div>
<!--1.导入Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script type="text/javascript">
    Vue.component('todo',{
      
      
        template:'<div>\
                <div>代办事项</div>\
                <ul>\
                    <li>学习狂神说Java</li>\
                </ul>\
            </div>'
    })
</script>

In the second step, we need to dynamically bind the title and value of the to-do item. How to do it? We can save a slot!
  1- Leave the above code for a slot, the slot

 Vue.component('todo',{
        template:'<div>\
                <slot name="todo-title"></slot>\
                <ul>\
                    <slot name="todo-items"></slot>\
                </ul>\
            </div>'
    });

2- Define a todo title component named todo-title and a todo content component named todo-items

Vue.component('todo-title',{
    
    
        props:['title'],
        template:'<div>{
    
    {title}}</div>'
    });
   
12345
//这里的index,就是数组的下标,使用for循环遍历的时候,可以循环出来!
    Vue.component("todo-items",{
    
    
        props:["item","index"],
        template:"<li>{
    
    {index+1}},{
    
    {item}}</li>"
    });

3- Instantiate Vue and initialize data

 var vm = new Vue({
    
    
        el:"#vue",
        data:{
    
    
            todoItems:['test1','test2','test3']
        }
    });

4- Insert these values, through the slot

<div id="vue">
    <todo>
        <todo-title slot="todo-title" title="秦老师系列课程"></todo-title>
        <!--<todo-items slot="todo-items" v-for="{item,index} in todoItems" v-bind:item="item"></todo-items>-->
        <!--如下为简写-->
        <todo-items slot="todo-items" v-for="item in todoItems" :item="item"></todo-items
    </todo>
</div>

Description: Our todo-title and todo-items components are distributed to the todo-title and todo-items slots of the todo component respectively. The
  complete code is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--view层,模板-->
<div id="vue">
    <todo>
        <todo-title slot="todo-title" title="title"></todo-title>
        <!--<todo-items slot="todo-items" v-for="{item,index} in todoItems" v-bind:item="item"></todo-items>-->
        <!--如下为简写-->
        <todo-items slot="todo-items" v-for="item in todoItems" :item="item"></todo-items
    </todo>
</div>
<!--1.导入Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
<script type="text/javascript">
    Vue.component('todo',{
      
      
        template:'<div>\
                <slot name="todo-title"></slot>\
                <ul>\
                    <slot name="todo-items"></slot>\
                </ul>\
            </div>'
    });
    Vue.component('todo-title',{
      
      
        props:['title'],
        template:'<div>{
      
      {title}}</div>'
    });
    //这里的index,就是数组的下标,使用for循环遍历的时候,可以循环出来!
    Vue.component("todo-items",{
      
      
        props:["item","index"],
        template:"<li>{
      
      {index+1}},{
      
      {item}}</li>"
    });

    var vm = new Vue({
      
      
        el:"#vue",
        data:{
      
      
            title:"秦老师系列课程",
            todoItems:['test1','test2','test3']
        }
    });
</script>
</body>
</html>

8.3. Custom events

Through the above code, it is not difficult to find that the data item is in the Vue instance, but the deletion operation must be completed in the component, so how can the component delete the data in the Vue instance? At this time, it involves parameter passing and event distribution. Vue is We provide a custom event function that helps us solve this problem; using this.$emit('custom event name', parameter), the operation process is as follows: 1-Add the methods object to the vue instance
  and Defines a method called removeTodoltems

var vm = new Vue({
        el:"#vue",
        data:{
            title_text:"秦老师系列课程",
            todoItems:['test1','test2','test3']
        },
        methods:{
            removeItems:function(index){
                console.log("删除了"+this.todoItems[index]+"OK");
                //splice() 方法向/从数组中添加/删除项目,然后返回被删除的项目,其中index
                this.todoItems.splice(index,1);
            }
        }
    });

2- Modify the code of the todo-items to-do content component, add a delete button, and bind the event!

 Vue.component("todo-items",{
        props:["item_p","index_p"],
        template:"<li>{
   
   {index_p+1}},{
   
   {item_p}} <button @click='remove'>删除</button></li>",
        methods:{
            remove:function (index) {
            //这里的remove是自定义事件名称,需要在HTML中使用v-on:remove的方式
                //this.$emit 自定义事件分发
                this.$emit('remove',index);
            }
        }
    });

3- Modify the HTML code of the todo-items to-do content component, add a custom event, such as remove, which can be bound to the method of the component, and then bound to the method of vue!

<!--增加了v-on:remove="removeTodoItems(index)"自定义事件,该组件会调用Vue实例中定义的-->
<todo-items slot="todo-items" v-for="(item,index) in todoItems"
                    :item_p="item" :index_p="index" v-on:remove="removeItems(index)" :key="index"></todo-items>

Modify the previous code to realize the delete function

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--view层,模板-->
<div id="vue">
    <todo>
        <todo-title slot="todo-title" :title="title_text"></todo-title>
        <!--<todo-items slot="todo-items" v-for="(item,index) in todoItems" v-bind:item="item"></todo-items>-->
        <!--如下为简写-->
        <todo-items slot="todo-items" v-for="(item,index) in todoItems"
                    :item_p="item" :index_p="index" v-on:remove="removeItems(index)" :key="index"></todo-items>
    </todo>
</div>
<!--1.导入Vue.js-->
<script src="../js/vue.js"></script>
<script type="text/javascript">
    Vue.component('todo',{
      
      
        template:'<div>\
                <slot name="todo-title"></slot>\
                <ul>\
                    <slot name="todo-items"></slot>\
                </ul>\
            </div>'
    });
    Vue.component('todo-title',{
      
      
        props:['title'],
        template:'<div>{
      
      {title}}</div>'
    });
    //这里的index,就是数组的下标,使用for循环遍历的时候,可以循环出来!
    Vue.component("todo-items",{
      
      
        props:["item_p","index_p"],
        template:"<li>{
      
      {index_p+1}},{
      
      {item_p}} <button @click='remove_methods'>删除</button></li>",
        methods:{
      
      
            remove_methods:function (index) {
      
      
                //this.$emit 自定义事件分发
                this.$emit('remove',index);
            }
        }
    });

    var vm = new Vue({
      
      
        el:"#vue",
        data:{
      
      
            title_text:"秦老师系列课程",
            todoItems:['test1','test2','test3']
        },
        methods:{
      
      
            removeItems:function(index){
      
      
                console.log("删除了"+this.todoItems[index]+"OK");
                this.todoItems.splice(index,1);
            }
        }
    });
</script>
</body>
</html>

logical understanding

insert image description here

8.4 Summary of getting started with Vue

Core: data-driven, componentized

Advantages: Drawing lessons from the modular development of AngularJS and the virtual Dom of React, the virtual Dom is to put the Demo operation in memory for execution;

Common attributes:

  • v-if
  • v-else-if
  • v-else
  • v-for
  • v-on binding event, abbreviated @
  • v-model data two-way binding
  • v-bind binds parameters to the giant sword, abbreviated as:

Componentization:

  • Composite component slot slot
  • The internal binding event of the component needs to be usedthis.$emit("事件名",参数);
  • Features of computed properties, caching computed data

Following the principle of SoC separation of concerns, Vue is a pure view framework and does not include communication functions such as Ajax. In order to solve communication problems, we need to use the Axios framework for asynchronous communication;

illustrate

The development of Vue is based on NodeJS. The actual development adopts Vue-cli scaffolding development, vue-router routing, and vuex for state management; for Vue UI, we generally use ElementUI (produced by Ele.me) or ICE (produced by Alibaba) for the interface. Let's quickly build the front-end project~~

Official website:

  • https://element.eleme.cn/#/zh-CN
  • https://ice.work/

9. The first vue-cli project

9.1. What is vue-cli

A scaffolding officially provided by vue-cli is used to quickly generate a vue project template; the
  pre-defined directory structure and basic code are like we can choose to create a skeleton project when creating a Maven project. This estimated project is scaffolding. Our development is faster;
  the function of the project

  • Unified directory structure
  • local debugging
  • hot deployment
  • unit test
  • Integrated packaging online

9.2. Required environment

  • Node.js: http://nodejs.cn/download/
      Installation is just the next step without thinking, install it in your own environment directory
  • Git: https://git-scm.com/doenloads
      Mirror: https://npm.taobao.org/mirrors/git-for-windows/

Confirm that nodejs is installed successfully:

  • Enter it under cmd node -vto see if the version number can be printed out correctly!
  • Enter it under cmd npm -vto see if the version number can be printed out correctly!
      This npm is a software package management tool, which is similar to the apt software installation under linux!
      If you install the Node.js Taobao Mirror Accelerator (cnpm)
      , the download will be much faster~
# -g 就是全局安装
npm install cnpm -g

# 或使用如下语句解决npm速度慢的问题
npm install --registry=https://registry.npm.taobao.org

The installation process may be a bit slow~, please be patient! Although cnpm is installed, try to use it sparingly!
  Where to install:C:\Users\administrator\AppData\Roaming\npm

insert image description here
  Install vue-cli

cnpm instal1 vue-cli-g
#测试是否安装成功#查看可以基于哪些模板创建vue应用程序,通常我们选择webpack
vue list

insert image description here

9.3. The first vue-cli application

1. Create a Vue project, we just create an empty folder on the computer, here I create a new directory under the D drive

D:\Project\vue-study;

2. Create a vue application based on the webpack template

#1、首先需要进入到对应的目录 cd D:\Project\vue-study
#2、这里的myvue是顶日名称,可以根据自己的需求起名
vue init webpack myvue

Just choose no all the way;
  instructions:

  • Project name: project name, press Enter by default
  • Project description: project description, press Enter by default
  • Author: The author of the project, press Enter by default
  • Install vue-router: whether to install vue-router, choose n not to install (you need to add it manually later)
  • Use ESLint to lint your code: Whether to use ESLint for code checking, choose n not to install (you need to add it manually later)
  • Set up unit tests: related to unit tests, choose n not to install (need to be added manually later)
  • Setupe2etests with Nightwatch: related to unit testing, choose n not to install (need to be added manually later)
  • Should we run npm install for you after the, project has been created: initialize directly after creation, select n, we execute it manually; run the result!

(1) Initialize and run

cd myvue
npm install
npm run dev

After the execution is complete, the directory has a lot of dependencies

When there is a problem, you can check the prompt and deal with it as follows
img

10. Use of webpack

10.1. What is Webpack

Essentially, webpack is a static module bundler for modern JavaScript applications. When webpack processes an application, it recursively builds a dependency graph that includes every module the application needs, and then packages all of these modules into one or more bundles. Webpack is the hottest thing right
  now Front-end resource modular management and packaging tool, which can package many loosely coupled modules into front-end resources that conform to production environment deployment according to dependencies and rules. It is also possible to separate the code of the modules loaded on demand, and then load them asynchronously when they are actually needed. Through loader conversion, any form of resource can be used as a module, such as Commons JS, AMD, ES 6, CSS, JSON, Coffee Script, LESS, etc.; with the tide of the mobile Internet, more and more websites today have changed from web page mode
  to Evolved to the WebApp mode. They run in modern browsers and use HTML 5, CSS 3, ES 6 and other new technologies to develop rich functions. Web pages are more than just fulfilling the basic needs of browsers; WebApp is usually a SPA (Single Page Application), Each view is loaded asynchronously, which leads to more and more JS codes being loaded during page initialization and use, which poses a huge challenge to the front-end development process and resource organization.
  The main difference between front-end development and other development work is that the front-end is based on multi-language, multi-level coding and organization work, and secondly, the delivery of front-end products is based on the browser, and these resources are run to the browser through incremental loading. , how to organize these fragmented codes and resources in the development environment, and ensure that they are loaded and updated quickly and gracefully on the browser side, requires a modular system. This ideal modular system is what front-end engineers have been working on for many years. Explore the puzzle.

10.2. The Evolution of Modularization

Script tag

	<script src = "module1.js"></script>
	<script src = "module2.js"></script>
	<script src = "module3.js"></script>

This is the most primitive way of loading JavaScript files. If each file is regarded as a module, then their interfaces are usually exposed in the global scope, that is, defined in the window object, and the calls of different modules have the same effect. area.
  This primitive loading method exposes some obvious drawbacks:

  • It is easy to cause variable conflicts in the global scope
  • Files can only <script>be loaded in the order in which they were written
  • Developers must subjectively resolve dependencies of modules and code bases
  • Various resources are difficult to manage in large-scale projects, and long-term accumulation of problems leads to messy code base

CommonsJS


NodeJS on the server side follows the CommonsJS specification. The core idea of ​​this specification is to allow modules to synchronously load other modules they need to depend on through the require method, and then export the interfaces that need to be exposed through exports or module.exports.

require("module");
require("../module.js");
export.doStuff = function(){
    
    };
module.exports = someValue;
1234

advantage:

  • Server-side modules are easy to reuse
  • There are already more than 450,000 module packages available in NPM
  • easy to use

shortcoming:

  • The synchronous module loading method is not suitable in the browser environment. Synchronization means blocking loading, and browser resources are loaded asynchronously
  • Cannot load multiple modules in parallel non-blocking

accomplish:

  • NodeJS on the server side
  • •Browserify, the CommonsJS implementation on the browser side, can use NPM modules, but the compiled and packaged files are large in size
  • modules-webmake, similar to Browserify, but not as flexible as Browserify
  • wreq, the predecessor of Browserify

AMD


The Asynchronous Module Definition specification actually has a main interface define(id?, dependencies?, factory); it specifies all the dependencies when declaring the module, and it is also passed as a formal parameter to the factory, and the dependent modules are executed in advance .

define("module",["dep1","dep2"],functian(d1,d2){
    
    
	return someExportedValue;
});
require(["module","../file.js"],function(module,file){
    
    });
1234

advantage

  • Suitable for loading modules asynchronously in the browser environment
  • Multiple modules can be loaded in parallel

shortcoming

  • Increased development costs, difficult to read and write code, poor semantics of module definition
  • Does not conform to the common modular way of thinking and is a compromised implementation

accomplish

  • RequireJS
  • curl

CMD


The Commons Module Definition specification is very similar to AMD, keeping it simple and maintaining great compatibility with the Modules specifications of CommonsJS and NodeJS.

define(function(require,exports,module){
    
    
	var $=require("jquery");
	var Spinning = require("./spinning");
	exports.doSomething = ...;
	module.exports=...;
});

advantage:

  • Depend on proximity, delayed execution
  • Can be easily run in NodeJS Cons
  • Relying on SPM packaging, the loading logic of the module is biased

accomplish

  • Sea.js
  • coolie

ES6 modules


The EcmaScript 6 standard adds a module system definition at the JavaScript language level. The design idea of ​​the ES 6 module is to make it as static as possible, so that the dependencies of the module and the variables of input and output can be determined at compile time. Both Commons JS and AMD modules can only determine these things at runtime.

import "jquery"
export function doStuff(){
    
    }
module "localModule"{
    
    }

advantage

  • Easy to perform static analysis
  • Future-proof Ecma Script standard

shortcoming

  • Native browsers have not yet implemented the standard
  • The new command is only supported by the new version of Node JS

accomplish

  • Babel

The module system that everyone expects
  can be compatible with a variety of module styles, and existing code can be used as much as possible. Not only JavaScript is modularized, but resources such as CSS, images, and fonts also need to be modularized.

10.3. Install Webpack

WebPack is a module loader and packaging tool, which can process and use various resources, such as JS, JSX, ES 6, SASS, LESS, pictures, etc., as modules.
  Install:

npm install webpack -g
npm install webpack-cli -g

The test installation was successful

  • webpack -v
  • webpack-cli -v

insert image description here

configuration

Create webpack.config.jsconfiguration file

  • entry: entry file, specify which file Web Pack uses as the entry of the project
  • output: output, specifying that WebPack puts the processed file to the specified path
  • module: module for processing various types of files
  • plugins: plugins, such as: hot update, code reuse, etc.
  • resolve: Set the path to point to
  • watch: monitor, used to package directly after setting the file change
module.exports = {
    
    
	entry:"",
	output:{
    
    
		path:"",
		filename:""
	},
	module:{
    
    
		loaders:[
			{
    
    test:/\.js$/,;\loade:""}
		]
	},
	plugins:{
    
    },
	resolve:{
    
    },
	watch:true
}

Directly run webpackthe command package

10.4. Using webpack

  1. create project
  2. Create a directory named modules to place resource files such as JS modules
  3. Create a module file under modules, such as hello.js, for writing JS module-related code
	//暴露一个方法:sayHi
	exports.sayHi = function(){
    
    
		document.write("<div>Hello Webpack</div>");
	}
  1. Create an entry file named main.js under modules to set the entry attribute when packaging
//require 导入一个模块,就可以调用这个模块中的方法了
var hello = require("./hello");
hello.sayHi();
  1. Create a webpack.config.js configuration file in the project directory and use the webpack command to package
module.exports = {
    
    
	entry:"./modules/main.js",
	output:{
    
    
		filename:"./js/bundle.js"
	}

}
  1. Create an HTML page in the project directory, such as index.html, and import the JS file packaged by webpack
	<!doctype html>
	<html lang="en">
		<head>
			<meta charset="UTF-8">
			<title>狂神说Java</title>
		</head>
		<body>
			<script src="dist/js/bundle.js"></script>
		</body>
	</html>
  1. Execute webpack directly in the IDEA console; if it fails, just run it with administrator privileges!
  2. Run HTML to see the effect

illustrate

# 参数--watch 用于监听变化
webpack --watch

Eleven, vue-router routing

11.1. Description


When studying, try to open the official document

Vue Router is the official routing manager for Vue.js. It is deeply integrated with the core of Vue.js, making it easy to build single-page applications. Included features are:

  • Nested routing/view tables
  • Modular, component-based routing configuration
  • Route parameters, queries, wildcards
  • View transition effect based on Vue js transition system
  • Fine-grained navigation control
  • Links with auto-activated CSS classes
  • HTML5 history mode or hash mode, automatically downgraded in IE 9
  • custom scrolling behavior

11.2. Installation

vue-cliTest and learn based on the first one
; first check whether there is vue-router in node modules   Vue-router is a plug-in package, so we still need to use n pm/cn pm to install it. Open the command line tool, enter your project directory, and enter the following command.

npm install vue-router --save-dev
1

If you use it in a modular project, you must explicitly install the routing function through Vue.use():

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter);

11.3. Testing

1. Delete useless things first
. 2. componentsStore components written by ourselves in the directory
. 3. Define a Content.vuecomponent of

<template>
	<div>
		<h1>内容页</h1>
	</div>
</template>

<script>
	export default {
      
      
		name:"Content"
	}
</script>

Main.vuecomponents

	<template>
	<div>
		<h1>首页</h1>
	</div>
</template>

<script>
	export default {
      
      
		name:"Main"
	}
</script>

4. Install the route, create a new folder in the src directory: router, to store the route specially, configure the route index.js, as follows

import Vue from'vue'
//导入路由插件
import Router from 'vue-router'
//导入上面定义的组件
import Content from '../components/Content'
import Main from '../components/Main'
//安装路由
Vue.use(Router) ;
//配置路由
export default new Router({
    
    
	routes:[
		{
    
    
			//路由路径
			path:'/content',
			//路由名称
			name:'content',
			//跳转到组件
			component:Content
			},{
    
    
			//路由路径
			path:'/main',
			//路由名称
			name:'main',
			//跳转到组件
			component:Mian
			}
		]
	});

5. main.jsConfigure routing in

import Vue from 'vue'
import App from './App'

//导入上面创建的路由配置目录
import router from './router'//自动扫描里面的路由配置

//来关闭生产模式下给出的提示
Vue.config.productionTip = false;

new Vue({
    
    
	el:"#app",
	//配置路由
	router,
	components:{
    
    App},
	template:'<App/>'
});

6. App.vueUse routing in

<template>
	<div id="app">
		<!--
			router-link:默认会被渲染成一个<a>标签,to属性为指定链接
			router-view:用于渲染路由匹配到的组件
		-->
		<router-link to="/">首页</router-link>
		<router-link to="/content">内容</router-link>
		<router-view></router-view>
	</div>
</template>

<script>
	export default{
      
      
		name:'App'
	}
</script>
<style></style>

12. Get Started Quickly

We adopt the practical teaching mode combined with the ElementUI component library, apply the required knowledge points to practice, and lead everyone to master the use of Vue as quickly as possible;

12.1. Create a project

Note: The command line must be run in administrator mode
1. Create a project named hello-vue vue init webpack hello-vue
2. Install dependencies. We need to install four plugins: vue-router, element-ui, sass-loader and node-sass

#进入工程目录
cd hello-vue
#安装vue-routern 
npm install vue-router --save-dev
#安装element-ui
npm i element-ui -S
#安装依赖
npm install
# 安装SASS加载器
cnpm install sass-loader node-sass --save-dev
#启功测试
npm run dev
123456789101112

3. Npm command explanation:

  • npm install moduleName: Install the module to the project directory
  • npm install -g moduleName:-g means to install the module globally, and the specific location on the disk depends on the location of npm config prefix
  • npm install -save moduleName: –save means to install the module into the project directory, and write dependencies in the dependencies node of the package file, -S is the abbreviation of this command
  • npm install -save-dev moduleName:–save-dev means to install the module into the project directory, and write dependencies in the devDependencies node of the package file, -D is the abbreviation of this command

12.2. Create a login page

Delete useless initialization stuff!
  Create the following structure in the source code directory:

  • assets: used to store resource files
  • components: used to store Vue functional components
  • views: used to store Vue view components
  • router: used to store vue-router configuration

insert image description here

Create a home page view and create a view component named Main.vue in the views directory:

<template>
	<div>首页</div>
</template>
<script>
	export default {
      
      
			name:"Main"
	}
</script>
<style scoped>
</style>
12345678910

Create a login page view Create a view component named Login.vue in the views directory, where the element of el-* is the ElementUI component;

<template>
  <div>
    <el-form ref="loginForm" :model="form" :rules="rules" label-width="80px" class="login-box">
      <h3 class="login-title">欢迎登录</h3>
      <el-form-item label="账号" prop="username">
        <el-input type="text" placeholder="请输入账号" v-model="form.username"/>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" placeholder="请输入密码" v-model="form.password"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" v-on:click="onsubmit('loginForm')">登录</el-button>
      </el-form-item>
    </el-form>

    <el-dialog title="温馨提示" :visible.sync="dialogVisiable" width="30%" :before-close="handleClose">
      <span>请输入账号和密码</span>
      <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogVisible = false">确定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
    export default {
      
      
        name: "Login",
      data(){
      
      
          return{
      
      
            form:{
      
      
              username:'',
              password:''
            },
            //表单验证,需要在 el-form-item 元素中增加prop属性
            rules:{
      
      
              username:[
                {
      
      required:true,message:"账号不可为空",trigger:"blur"}
              ],
              password:[
                {
      
      required:true,message:"密码不可为空",tigger:"blur"}
              ]
            },

            //对话框显示和隐藏
            dialogVisible:false
          }
      },
      methods:{
      
      
          onSubmit(formName){
      
      
            //为表单绑定验证功能
            this.$refs[formName].validate((valid)=>{
      
      
              if(valid){
      
      
                //使用vue-router路由到指定界面,该方式称为编程式导航
                this.$router.push('/main');
              }else{
      
      
                this.dialogVisible=true;
                return false;
              }
            });
          }
      }
    }
</script>

<style lang="scss" scoped>
  .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 0 25px #909399;
  }
  .login-title{
      
      
    text-align:center;
    margin: 0 auto 40px auto;
    color: #303133;
  }
</style>

index.jsCreate a route and create a vue-router routing configuration file named vue-router in the router directory

import Vue from 'vue'
import VueRouter from 'vue-router'
import Main from '../views/Main'
import Login from '../views/Login'

Vue.use(VueRouter);

export default new VueRouter({
    
    
  routes:[
    {
    
    
      path:'/login',
      name:'login',
      component:Main
    },{
    
    
    path: '/main',
      name:'main',
      component: Login
    }
  ]
});

APP.view

<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

<script>


export default {
      
      
  name: 'App',

}
</script>

<style>
#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;
}
</style>

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)
})

Guess you like

Origin blog.csdn.net/kalvin_y_liu/article/details/125832460