VUE Notes - Bilibili Kuangshen said

Vue notes

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".
insert image description here

1. Front-end core analysis

1.1. Overview of
the Soc principle: the principle of 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: show the user, refresh the data given by the background

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. It is used to control the behavior of web
    pages
    .

1.4. Presentation layer (CSS)
CSS cascading style sheet is a markup language, not a programming language, so it cannot customize variables, cannot quote, 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 being sent to the client to run. Instead, the character code in text format is sent to the browser, which interprets and runs it.

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 construction tool
  • 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 sequence
    Note: The above knowledge points have sorted out all the skills required for WebApp development

2.3. The main purpose of hybrid development (Hybrid App) 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 two main packaging methods:

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

Wechat applets
See WeChat official website for details. 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 in order to facilitate development, but our Java back-end staff know that the background knowledge system is extremely It is huge 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

  • iView
    iview is a powerful Vue-based UI library. There are 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.
    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.
    Remarks: It belongs to the front-end mainstream framework, and it can be considered when selecting models. The main feature is that it supports more desktops

  • ICE
    Feibing is a React/Angular/Vue-based mid-background application solution of the Alibaba team. Within Alibaba, more than 270 projects from almost all BUs are already 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.
    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.

  • at-ui
    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.

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

  • 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.
    Remarks: Produced by Google, the main feature is to quickly build native APP applications, such as hybrid applications, this framework is a mandatory framework

  • lonic
    lonic is both a CSS framework and a Javascript UI library, lonic 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.

  • WeChat applet

  • mpvue
    mpvue is a front-end framework developed by Meituan that uses Vue.js to develop small programs. It currently supports WeChat small programs, Baidu smart small programs, Toutiao small programs and Alipay small programs. The framework is based on Vue.js, and the modified runtime framework runtime and code compiler compiler are implemented so that they can run in the applet environment, thus introducing Vue.js development experience for applet development.
    Remarks: Complete Vue development experience, and supports multi-platform small program development, recommended

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

3. Understand the evolution history of front-back separation

Why do you need to separate the front and back
? 3.1 Back-end-based MVC era
In order to reduce the complexity of development, the back-end is the starting point. For example, the use of frameworks such as Struts and Spring MVC is the back-end MVC era; take the SpringMVC process as an example
:
insert image description here

  • Initiate a request to the front controller (Dispatcher Servlet)
  • The front controller requests HandlerMapping to find Handler, which can be searched according to xml configuration and annotations
  • The processor mapper HandlerMapping returns a Handler to the front controller
  • The front controller calls the processor adapter to execute the Handler
  • Processor adapter to execute Handler
  • Handler execution completes and returns ModelAndView to the adapter
  • The processor adapter returns ModelAndView to the front controller, and ModelAndView is an underlying object of the SpringMvc framework, including Model and View
  • The front controller requests the view parser to perform view parsing, and parses it into a real view (JSP) according to the logical view name
  • The view resolver returns the View to the front controller
  • The front controller performs view rendering, and the view rendering fills the model data (in the ModelAndView object) into the request field
  • The front controller responds with results to the user

Advantages
MVC is a very good collaboration model, which can effectively reduce the coupling of code. From the perspective of architecture, developers can 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, AOAX (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 post dog skin plaster advertisements on web pages) SPA (Single Page Application) single page application era.
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, browser-side layered architecture began to appear in this era:
insert image description here
Disadvantages
Front-end interface agreement: If the back-end interface is messed up, if the back-end business model is not stable enough, front-end development will be very painful; many teams have similar attempts, Do it through interface rules, interface platforms, etc. 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* mode 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: Angular JS, React, Vue.js, Ember JS, etc. The general principle of these frameworks is to first Layered by type, such as Templates, Controllers, Models, and then segmented within the layer, as shown in the figure below:
    insert image description here
    Advantages
  • 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* mode has solved many problems, but as mentioned above, there are still many shortcomings. With the rise of Node JS, JavaScript has the ability to run on the server side. This means that there can be a new R&D model:

In this R&D 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
In summary, no matter whether the model is good or the technology is good or bad, there is no distinction between good and bad, only suitable or not; the development idea of ​​separating front and back is mainly based on Soc (principle of separation of attention), and all the above modes are all Make the front-end and back-end responsibilities clearer, and the division of labor more reasonable and efficient.

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, simple Developed by Ken Cooper and Ted Peters, architects Ken Cooper and Ted Peters, 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 include Vue.js, Anfular JS
4.2, why use MVVM
MVVM mode is the same as MVC mode, 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.

MVVM components
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 unified interface rules with the front-end
(3) ViewModel
ViewModel is a view data layer generated and maintained by 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 the updated data view will be automatically updated accordingly, truly realizing event-driven programming.
  The View layer does not display the data of the Model layer, but the data of the ViewModel. The ViewModel is responsible for interacting with the Model layer, which completely decouples the View layer and the Model layer. This decoupling is crucial, and it is the separation of the front and back ends. An important part of program implementation .
  
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 monitor 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)
The core of code writing Vue.js is to realize the MVVM mode, and the role she plays is the View Model layer, so the so-called first application is to display her data binding function, and the operation process is as follows: 1. Create
a HTML file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--1.导入vue.js-->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
</head>
<body>
<div id="app">
    {
   
   {message}}
</div>
<script>
     let vm = new Vue({
      
      
        el: "#app",
        data: {
      
      
            message: "hello,vue"
        }
    });
</script>
</body>
</html>

illustrate:

  • el: '#vue': the 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 is set!

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?
(3) 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 developer tool
  2, enter vm.message='HelloWorld' in 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 Value, data can be omitted in the middle. In this operation, I did not actively manipulate the DOM, so the content of the page changed. This is realized with the help of Vue's data binding function; View Model is required in the MV VM mode The layer is to use the observer mode to realize the monitoring and binding of data, so as to achieve the rapid response of data and view.

5. Basic Grammatical Instructions

5.1, v-bind
We have successfully created our first Vue application! It seems that this is very similar to rendering a string template, but Vue has done 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.
  
5.2, v-if, v-else
What is a conditional judgment statement, I don’t need to explain it, the following two attributes! The code on
v-if
v-else

<!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 vm.ok=false in the console and press Enter, you will find that the content displayed in the browser will directly change to NO
  Note: Use the v-* attribute Binding data does not require
v-else-if
v-if
v-else-if
v-else wrapped
in double curly braces ) 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>

5.3, v-for
v-for
format description

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

</div>

Note: items is an array, and item 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 vm.items.push({message: 'Mad God said operation and maintenance'}) in the console, try to add a piece of data, you will find that the content displayed in the browser will add a mad god said operation and maintenance.

5.4, ​​v-on
v-on listens to event
 emsp; events include Vue events and some events on the front-end page itself! Our click here is a vue event, which can be bound to the method events in methods 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 a 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 will also change 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.
  
Why do we need to realize the two-way binding of data?
In Vue.js, if you use vuex, the data is actually one-way. The reason why it is said to be two-way binding of data is that it is used for UI controls. For us to process forms, Vue The two-way data binding of .js 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 the v-model directive 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. Despite its magic, v-model is 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: v-model ignores the initial values ​​of the value, checked, and selected attributes 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 component's data option via JavaScript!

(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>

(5) 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>

(6) 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: The initial value of the v-model 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 in this case, iOS does not fire the change event. Therefore, it is more recommended to provide a disabled option with an empty value as above.

6.3. What is a component? A component
is a reusable Vue instance. To put it bluntly, it is a set of reusable templates. It is similar to JSTL's custom tags, Thymeleal's th:fragment and other frameworks. Usually an application will use a organized as a tree of nested components:
for example, you might have components such as a header, sidebar, content area, etc., each of which contains other components such as navigation links, blog posts, etc.

(1) Note for the first Vue component
: In actual development, we will not use the following methods to develop components, but use vue-cli to create and develop vue template files. The following methods are just to let everyone understand what a component is .
  Use the Vue.component() method to register components in the following format:

<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: the template of the component

(2) Use the props attribute to pass parameters
It doesn't make any sense to use components like the above, so we need to pass parameters to the component, then we need to use the props attribute!
  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>

illustrate:

  • v-for="item in items": traverse the array named items defined in the Vue instance and create the same number of components
  • v-bind:panh="item": Bind the traversed item to the item attribute defined in props in the component; the panh on the left of the = sign is the attribute name defined by props, and the one on the right is the traversed item in item in items item value

Seven, 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 function is to realize AJAX asynchronous communication. Its features are as follows:

  • Create XMLHttpRequests from the browser
  • 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.js is a view layer framework and the author (You Yuxi) strictly abides by the SoC (principle of separation of concerns), Vue.js does not include the AJAX communication function. In order to solve the communication problem, the author A plugin called vue-resource was developed separately, but after entering version 2.0, the maintenance of the plugin was stopped and the Axios framework was recommended. Use less jQuery, because it operates the Dom too frequently! 7.3 . Most of the interfaces we developed for the
  
first Axios application
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 file and fill in the above content, put it in the root directory of the project

{
  "name": "狂神说Java",
  "url": "https://www.baidu.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">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--在线CDN-->
    <!--1.导入vue.js-->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
    <!--导入axios-->
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.19.2/axios.min.js"></script>

</head>
<body>

<div id="app">
    <div>{
   
   {info.name}}</div>
    <a v-bind:href="info.url">点我到百度链接</a>
</div>

<script>

    let vm = new Vue({
      
      
        el: "#app",
        //和data: 不同 属性:vm
        //data()是方法
        data() {
      
      
            //return接收 (也可以不写return)
            return {
      
      
                // info: {
      
      
                //     name:null,
                //     url:null,
                // },

                //这样写也行,this.info=a.data自动装配
                info:null
            }
        },
        mounted() {
      
      
            //钩子函数 链式编程 ES6新特性
            //匿名函数,a是参数,后面是方法体
            axios.get("data.json").then(a => (this.info=a.data));
        }
    });
</script>

</body>
</html>

illustrate:

  • Here, v-bind is used to bind the attribute value 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 into the data object of the Vue instance
  • Our data structure in data must match the data format returned by Ajax response!

7.4.
  Official documentation of Vue's life cycle: 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 initial stage data , Compiling templates, mounting DOM, rendering-updating-rendering, unloading and a series of processes, 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

8.1. What is a computed attribute?
The focus of a computed attribute is on the word attribute (attribute is a noun). First, it is an attribute. Secondly, this attribute has the ability to calculate (calculate is a verb). The calculation here is a function: simply put , it is a property that can cache the calculation result (convert the behavior into a static property), nothing more; it can be imagined as a cache!

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <!--在线CDN-->
    <!--1.导入vue.js-->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
</head>
<body>

<div id="app">
    <p>c0</p>
    <p>c1:{
   
   {currentTime1()}}</p>
    <p>c2:{
   
   {currentTime2}}</p>
</div>

<script>
    let vm = new Vue({
      
      
        el: "#app",
        data: {
      
      
            message: "hello lcl"
        },
        methods: {
      
      
            currentTime1: function () {
      
      
                return Date.now();//返回一个时间戳
            }
        },
        //计算属性
        computed: {
      
      
            currentTime2: function () {
      
      
                // 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! 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 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 time, you can consider caching the result. Using the calculation attribute can It is very convenient to do this. The main feature of the calculated 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 elements as the outlet for carrying and distributing content , the author calls it a slot, which can be applied in the scene of combining components;

The test
is like preparing to make a todo component (todo), which is composed of a todo title (todo-title) and a todo content (todo-items), but these three components are independent of each other, how to operate it ?
Notev:bind: can be abbreviated to a colon:
  v-on: can be abbreviated to an @

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <!--1.导入vue.js-->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
</head>

<body>

<div id="app">
    <todo>
        <todo-title slot="slot1" v-bind:title="title"></todo-title>
        <todo-items slot="slot2" v-for="todoitem in todoItems" :item="todoitem"></todo-items>
    </todo>

</div>


<script>
    //slot 插槽 这个组件要定义在前面不然出不来数据
    Vue.component("todo", {
      
      
        template: '<div>\
                        <slot name="slot1"></slot>\
                        <ul>\
                        <slot name="slot2"></slot>\
                        </ul>\
                    <div>'
    });

    Vue.component("todo-title", {
      
      
        //属性
        props: ['title'],
        template: '<div>{
      
      {title}}</div>'
    });

    Vue.component("todo-items", {
      
      
        props: ['item'],
        template: '<li>{
      
      {item}}</li>'
    });

    //let vm = new Vue放最后
    let vm = new Vue({
      
      
        el: "#app",
        data: {
      
      
            //标题
            title: "图书馆系列图书",
            //列表
            todoItems: ['三国演义', '红楼梦', '西游记', '水浒传']
        }
    });
</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? This involves parameter passing and events Distributed, Vue provides us with the function of custom events to help us solve this problem; use this.$emit('custom event name', parameter) code
:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <!--1.导入vue.js-->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
</head>

<body>

<div id="app">
    <todo>
        <todo-title slot="slot1" v-bind:title="title"></todo-title>
<!--      @rmv="removeItem(index) 让前端绑定到vue实例的方法  -->
<!--      v-for会默认返回index下标-->
        <todo-items slot="slot2" v-for="(todoitem,index) in todoItems" :item="todoitem"  @rmv="removeItem(index)"></todo-items>
    </todo>

</div>

<script>
    //slot 插槽 这个组件要定义在前面不然出不来数据
    Vue.component("todo", {
      
      
        template: '<div>\
                        <slot name="slot1"></slot>\
                        <ul>\
                        <slot name="slot2"></slot>\
                        </ul>\
                    <div>'
    });

    Vue.component("todo-title", {
      
      
        //属性
        props: ['title'],
        template: '<div>{
      
      {title}}</div>'
    });

    Vue.component("todo-items", {
      
      
        props: ['item'],
        //只能绑定当前组件方法
        template: '<li>{
      
      {item}} <button @click="remove">删除</button>  </li>',
        methods:{
      
      
            remove: function (){
      
      
                //this.$emit(“事件名”,参数) 自定义事件分发,调用前端的方法
                this.$emit('rmv');
            }
        }
    });

    //let vm = new Vue放最后
    let vm = new Vue({
      
      
        el: "#app",
        data: {
      
      
            //标题
            title: "图书馆系列图书",
            //列表
            todoItems: ['三国演义', '红楼梦', '西游记', '水浒传']
        },
        methods: {
      
      
            removeItem:function (index){
      
      
                //从index开始删除一个元素
                this.todoItems.splice(index,1);
            }
        }
    });
</script>
</body>
</html>

Two-way binding between front end and vue instance , component and front end binding, component cannot directly use vue instance
insert image description here
8.4, Vue entry summary
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;

Commonly used attributes :
v-if
v-else-if
v-else
v-for
v-on binding event, abbreviated @
v-model data two-way binding
v-bind to component binding parameters, abbreviated:

Componentization :

  • Composite component slot slot
  • The internal binding event of the component needs to use this.$emit("event name", parameter);
  • 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;

Explain that
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. ) to quickly build a 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 scaffold officially provided by vue-cli is used to quickly generate a vue project template; the
  pre-defined directory structure and basic code are just like we can choose to create a skeleton project when creating a Maven project , this estimated project is scaffolding, and our development is faster;
  project functions
  - unified directory structure
  - local debugging
  - hot deployment
  - unit testing
  - integrated packaging and online

9.2. Required environment
Node.js : http://nodejs.cn/download/
Git : https://git-scm.com/doenloads
Mirror : https://npm.taobao.org/mirrors/git-for- windows/
Confirm that nodejs is installed successfully:
Enter node -v in cmd to check whether the version number can be printed out correctly!
Enter npm -v under cmd to 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!

#安装Node.js淘宝镜像加速器(cnpm),这样的话,下载会快很多~
#-g 就是全局安装
npm install cnpm -g
#或每次使用加上如下语句解决npm速度慢的问题
npm install --registry=https://registry.npm.taobao.org

Default installation location: C:\Users\administrator\AppData\Roaming\npm
(if the environment variable is configured, it will be where the environment variable is located, such as mine in D:\devloper_tools\nodejs\node_global)
insert image description here
install vue-cli

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

As shown in the picture:
insert image description here
insert image description here

One more vue-cli folder
insert image description here
9.3, the first vue-cli application
1. Create a Vue project, create an empty folder
2. Create a vue application based on webpack template

#1、首先需要进入到对应的目录 cd D:\fg_project\webstormProject\vueStudy2
#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!
    insert image description here
    Check:
    insert image description here

3. Initialize and run

cd myvue
npm install
npm run dev

insert image description here
After the execution is complete, the directory has a lot of dependencies
insert image description here
insert image description here
Access:
insert image description here
Stop: Ctrl + C

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. Modular Evolution
Script Tags

<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 be loaded in the order in which scripts are 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

NodeJS on the CommonsJS
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;

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

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

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

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

Implement
RequireJS
curl

The CMD
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

Implement
Sea.js
coolies

The ES6 module
EcmaScript 6 standard adds the module system definition at the JavaScript language level. The design idea of ​​ES 6 modules is to make them as static as possible, so that the dependencies of the modules, as well as the input and output variables 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

Implement
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.js configuration file

  • entry: entry file, specify which file Web Pack uses as the entry of the project
  • output: output, specifying that WebPack places the processed file in 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 changes
module.exports = {
    
    
	entry:"",
	output:{
    
    
		path:"",
		filename:""
	},
	module:{
    
    
		loaders:[
			{
    
    test:/\.js$/,;\loade:""}
		]
	},
	plugins:{
    
    },
	resolve:{
    
    },
	watch:true
}

Directly run the webpack command to package
10.4, use webpack
to create a project
Create a directory named modules to place resource files such as JS modules
Create module files under modules, such as hello.js, to write code related to JS modules

//暴露一个方法:sayHi
exports.sayHi = function(){
    
    
	document.write("<div>Hello Webpack</div>");
}

Create an entry file named main.js under modules to set the entry attribute when packaging

//require 导入一个模块,就可以调用这个模块中的方法了
var hello = require("./hello");
hello.sayHi();

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

}

Execute webpack directly in the console; if it fails, just run it with administrator privileges!
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>

Run HTML to see the effect

illustrate

# 参数--watch 用于监听变化(热部署)
webpack --watch

Eleven, vue-router routing

11.1. Explain that Vue
Router is the official routing manager of 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. The installation
  is based on the first vue-cli for testing and learning; 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. Open the command line tool, enter your project directory, and enter the following command.

npm install vue-router --save-dev

insert image description here

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. Test
1. Delete useless things first
. 2. Store components written by ourselves in the components directory
. 3. Define a Content.vue component

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

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

Main.vue component

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

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

4. Install the route. In the src directory, create a new folder: router, which is dedicated to storing routes, and configure 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:Main
			}
		]
	});

5. Configure routing in main.js

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. Use routing in App.vue

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

insert image description here

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. Installation dependencies, we need to install four plug-ins: 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

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 things!
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>
<h1>首页</h1>
</template>

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

<style scoped>

</style>

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="dialogVisible"
      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: '密码不可为空', trigger: '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>

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

import Vue from 'vue'
import Router from 'vue-router'
//导入组件
import Main from "../views/Main";
import Login from "../views/Login";


//使用
Vue.use(Router);
//导出
export default new Router({
    
    
  routes: [
    {
    
    
      //登录页
      path: '/main',
      component: Main
    },
    //首页
    {
    
    
      path:'/login',
      component: Login
    },
  ]

})

APP.view

<template>
  <div id="app">

    <router-view></router-view>
  </div>
</template>

<script>


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

<style>

</style>

main.js

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)

new Vue({
    
    
  el: '#app',
  router,
  render: h=>h(App)

})

Test: Open http://localhost:8080/#/login in the browser
insert image description here

If there is an error: It may be a compilation error caused by the version of sass-loader being too high. The current highest version is 8.0.2 and needs to be returned to 7.3.1; go to the
"sass-loader" version in the package.json file and replace it with 7.3.1, and then restart cnpm install;

12.3. Routing nesting
Nested routing is also called sub-routing. In practical applications, it is usually composed of multi-layer nested components.

1. Create a user information component, and create a view component named Profile.vue in the views/user directory;

<template>
  <h1>个人信息</h1>
</template>

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

<style scoped>

</style>

2. In the user list component, create a view component named List.vue under the views/user directory;
List.vue

<template>
  <h1>用户列表</h1>

</template>

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

<style scoped>

</style>

3. To modify the home page view, we modify the Main.vue view component, where the ElementUI layout container component is used, the code is as follows:
Main.vue

<template>
  <div>
    <el-container>
      <el-aside width="200px">
        <el-menu :default-openeds="['1']">
          <el-submenu index="1">
            <template slot="title"><i class="el-icon-caret-right"></i>用户管理</template>
            <el-menu-item-group>
              <el-menu-item index="1-1">
                <!--插入的地方-->
                <router-link to="/user/profile">个人信息</router-link>
              </el-menu-item>
              <el-menu-item index="1-2">
                <!--插入的地方-->
                <router-link to="/user/list">用户列表</router-link>
              </el-menu-item>
            </el-menu-item-group>
          </el-submenu>

          <el-submenu index="2">
            <template slot="title"><i class="el-icon-caret-right"></i>内容管理</template>
            <el-menu-item-group>
              <el-menu-item index="2-1">分类管理</el-menu-item>
              <el-menu-item index="2-2">内容列表</el-menu-item>
            </el-menu-item-group>
          </el-submenu>

          <el-submenu index="3">
            <template slot="title"><i class="el-icon-caret-right"></i>系统设置</template>
            <el-menu-item-group>
              <el-menu-item index="3-1">用户设置</el-menu-item>
            </el-menu-item-group>
          </el-submenu>

        </el-menu>
      </el-aside>

      <el-container>
        <el-header style="text-align: right; font-size: 12px">
          <el-dropdown>
            <i class="el-icon-setting" style="margin-right: 15px"></i>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>个人信息</el-dropdown-item>
              <el-dropdown-item>退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-header>
        <el-main>
          <!--在这里展示视图-->
          <router-view />
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>
<script>
export default {
      
      
  name: "Main"
}
</script>
<style scoped lang="scss">
.el-header {
      
      
  background-color: #B3C0D1;
  color: #333;
  line-height: 60px;
}
.el-aside {
      
      
  color: #333;
}
</style>

4. Configure nested routing Modify the index.js routing configuration file in the router directory, use children to put it in main and write it into submodules, the code is as follows
index.js

import Vue from 'vue'
import Router from 'vue-router'
//导入组件
import Main from "../views/Main";
import Login from "../views/Login";
//导入子模块
import UserList from "../views/user/List";
import UserProfile from "../views/user/Profile";

//使用
Vue.use(Router);
//导出
export default new Router({
    
    
  routes: [
    {
    
    
      //登录页
      path: '/main',
      component: Main,
      //  写入子模块
      //写在里面才是页内跳转,写在外面由app.vue管理
      children: [
        {
    
    
          path: '/user/profile',
          component: UserProfile,
        },
        {
    
    
          path: '/user/list',
          component: UserList,
        },
      ]
    },
    //首页
    {
    
    
      path:'/login',
      component: Login
    },

    //测试:写在外面。不是页面内跳转了
    // {
    
    
    //   path: '/user/profile',
    //   component: UserProfile,
    // },
  ]
})

Effect:
insert image description here
12.4. Parameter passing
Here is a demonstration of how to pass if the request has parameters.
Use the code of the above example to modify some codes and do not put repeated codes here.
The first value method
1. Modify the routing configuration, mainly under the router A placeholder like id is added to the path attribute in index.js

{
    
    
	path: '/user/profile/:id', 
	name:'UserProfile', 
	component: UserProfile
}

2. Passing parameters
  At this time, we changed the to at the route-link position in Main.vue to: to, in order to use this attribute as an object. Note that the name attribute name in router-link must be the same as the name in the route The attribute name matches, because Vue can find the corresponding routing path;

<!--name是组件的名字 params是传的参数 如果要传参数的话就需要用v:bind:来绑定-->
<router-link :to="{name:'UserProfile',params:{id:1}}">个人信息</router-link>

3. Receive parameters in the component Profile.vue to be displayed Use { {$route.params.id}} to receive
part of the code of Profile.vue

<template>
  <!--  所有的元素必须在根节点下-->
  <div>
    <h1>个人信息</h1>
    {
   
   {$route.params.id}}
  </div>
</template>

The second method of value acquisition uses props to reduce coupling
1. Modify the routing configuration, mainly 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. Pass parameters and modify the route-link address in Main.vue as before

<!--name是组件的名字 params是传的参数 如果要传参数的话就需要用v:bind:来绑定-->
<router-link :to="{name:'UserProfile',params:{id:1}}">个人信息</router-link>

3. Receive parameters in Profile.vue to add props attribute
Profile.vue to the target component

<template>
  <div>
    个人信息
    {
   
   { id }}
  </div>
</template>
<script>
    export default {
      
      
      props: ['id'],
      name: "UserProfile"
    }
</script>
<style scoped>
</style>

12.5. Component redirection
Everyone understands the meaning of redirection, but redirection in Vue is used when the paths are different but the components are the same, for example: the
configuration of index.js under the router

{
    
    
  path: '/main',
  name: 'Main',
  component: Main
},
{
    
    
  path: '/goHome',
  redirect: '/main'
}

Explanation: Two paths are defined here, one is /main and the other is /goHome, where /goHome is redirected to the /main path, so it can be seen that redirection does not need to define components; if it is used, it only needs to be in
Main.vue Just set the corresponding path;

<el-menu-item index="1-3">
    <router-link to="/goHome">回到首页</router-link>
</el-menu-item>

12.6. Routing mode and 404
routing mode have two kinds of
hash: path with # symbol, such as http://localhost/#/login
history: path without # symbol, such as http://localhost/login
Modify the routing configuration, the code is as follows :

export default new Router({
    
    
  mode: 'history',
  routes: [
  ]
});

404 demo
1. Create a NotFound.vue view component
NotFound.vue

<template>
    <div>
      <h1>404,你的页面走丢了</h1>
    </div>
</template>
<script>
    export default {
      
      
        name: "NotFound"
    }
</script>
<style scoped>
</style>

2. Modify the routing configuration index.js

import NotFound from '../views/NotFound'
{
    
    
   path: '*',
   component: NotFound
}

12.7. Routing hooks and asynchronous requests
beforeRouteEnter: execute before entering the route
beforeRouteLeave: execute before leaving the route

Write in Profile.vue

  export default {
    
    
    name: "UserProfile",
    beforeRouteEnter: (to, from, next) => {
    
    
      console.log("进入个人信息页前");
      next();
    },
    beforeRouteLeave: (to, from, next) => {
    
    
      console.log("离开个人信息页前");
      next();
    }
  }

Parameter description:
to: the path information that the route will jump to
from: the path information before the path jump
next: the control parameter of the route
next() jumps to the next page
next('/path') changes the jump direction of the route so that It jumps to another route
next(false) returns to the original page
next((vm)=>{}) is only available in beforeRouteEnter, vm is a component instance

Use asynchronous requests in hook functions
1. Install Axios

cnpm install --save vue-axios

2. main.js references Axios

import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)

3. Prepare data: Only the files in our static directory can be accessed, so we put the static files in this directory.
The data is the same as the json data used before, and it needs to go to the above axios example

// 静态数据存放的位置
static/mock/data.json


4. Make an asynchronous request Profile.vue in beforeRouteEnter

  export default {
    
    
    //第二种取值方式
    // props:['id'],
    name: "UserProfile",
    //钩子函数 过滤器
    beforeRouteEnter: (to, from, next) => {
    
    
      //加载数据
      console.log("进入路由之前")
      next(vm => {
    
    
        //进入路由之前执行getData方法
        vm.getData()
      });
    },
    beforeRouteLeave: (to, from, next) => {
    
    
      console.log("离开路由之前")
      next();
    },
    //axios
    methods: {
    
    
      getData: function () {
    
    
        this.axios({
    
    
          method: 'get',
          url: 'http://localhost:8080/static/mock/data.json'
        }).then(function (response) {
    
    
          console.log(response)
        })
      }
    }
  }

Effect:
insert image description here
end


Reprinted from:
Author: None1014
Address: https://www.cnblogs.com/none-space/p/14457581.html
(some pictures are attached, some codes are modified)
,
reference article: https://blog.csdn .net/okForrest27/article/details/106849246

Guess you like

Origin blog.csdn.net/weixin_44732379/article/details/116779908