Home  >  Article  >  Web Front-end  >  Vue’s most detailed knowledge and notes

Vue’s most detailed knowledge and notes

WBOY
WBOYforward
2021-12-20 11:14:593738browse

This article brings you the most complete and detailed knowledge of Vue. In order to understand, understand and master the front-end, I hope it will be helpful to everyone!

1. Front-end core analysis

1.1. Overview

Soc principle: separation of concerns principle

Vue The core library only focuses on the view layer, making it easy to integrate with third-party libraries or existing projects.

HTML CSS JS: View: Show it to the user, refresh the data provided 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): super Hyper Text Markup Language (Hyper Text Markup Language), determines the structure and content of web pages
  • CSS (Performance): Cascading Style Sheets (Cascading Style Sheets), sets the presentation style of web pages.
  • 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 ,Structural layer(HTML)

Too simple, a little bit

1.4. Presentation layer (CSS)

CSS cascading style sheet is a markup language , is not a programming language, so you cannot customize variables, reference, etc. In other words, it does not have any syntax support. Its main flaws are as follows:

  • The syntax is not powerful enough, such as the inability to nest. Writing, resulting in the need to write many repeated selectors in modular development;
  • There is no variable and reasonable style reuse mechanism, so that logically related attribute values ​​​​must be repeatedly output in the form of literals, making it difficult to maintain ;
    This has resulted in an unreasonable increase in 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 missing in CSS, reduce redundant code, and improve the maintainability of style code. It greatly improves the efficiency of front-end style development.

What is CSS preprocessor

The CSS preprocessor defines a new language. The basic idea is to use a specialized programming The language adds some programming features to CSS, uses CSS as a target to generate files, and then developers only need to use this language to code CSS. Translated into easy-to-understand words, it means "Use a specialized programming language to design the Web page style, and then convert it into a normal CSS file through a compiler for use in the project".

What are the commonly used CSS preprocessors

  • SASS: Based on Ruby, processed through the server, it is powerful. High analysis efficiency. You need to learn the Ruby language, which is more difficult to get started than LESS.
  • LESS: Based on NodeJS, processed through the client, easy to use. The function is simpler than SASS, and the parsing efficiency is also lower than SASS, but it is sufficient in actual development, so if our backend 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 for running. Instead, it is converted into text format The character code is sent to the browser, which is interpreted and run by the browser.

Native Native JS development

Native JS development means that we follow the [ECMAScript] standard development method, referred to as ES. The characteristic is that all browsers support 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, current mainstream version: webpack packaging becomes ES5 support)
  • ES7
  • ES8
  • ES9 (draft stage)

The difference is that new features are gradually added.
TypeScript Microsoft's Standard
TypeScript is a free and open source programming language developed by Microsoft. It is a superset of JavaScript, and essentially adds optional static typing and class-based object-oriented programming to the language. Led by Anders Helsberg (father of C#, Delphi, TypeScript; founder of .NET). The characteristic 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. Therefore, many browsers cannot directly support TypeScript syntax and need to be compiled (compiled into JS) before it can be correctly executed by the browser. .

JavaScript Framework

  • JQuery: A well-known JavaScript library. The advantage is that it simplifies DOM operations. The disadvantage is that DOM operations are too frequent, which affects front-end performance; in the eyes of the front-end, it is only used to be compatible with IE6, 7, and 8;
  • Angular: The front-end framework acquired by Google was developed by a group of Java programmers. It is characterized by moving the MVC model in the background to the front-end and adding the modular development concept. It cooperates with Microsoft and adopts TypeScript syntax development; friendly to back-end programmers, but not 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; as of the time of publishing the blog Angular6 has been launched)
  • React: Produced by Facebook, a high-performance JS front-end framework; characterized by a new concept [virtual DOM] used to reduce real DOM operations and simulate DOM operations in memory, effectively It improves the efficiency of front-end rendering; the disadvantage is that it is complicated to use, because you need to learn an additional [JSX] language;
  • Vue: a progressive JavaScript framework, the so-called progressive means to gradually implement new features, such as Implement new features such as modular development, routing, and state management. Its characteristic is that it combines the advantages of Angular (modularity) and React (virtual DOM);
  • Axios: front-end communication framework; because the boundaries of Vue are very clear, it is to process DOM, so it does not have communication capabilities. At this time, you need to use an additional communication framework to interact with the server; of course, you can also directly choose to use the AJAX communication function provided by jQuery;

2. Front-end development history

2.1. UI framework

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

2.2, JavaScript construction tool

  • Babel: JS compilation tool, mainly used for new ES features not supported by browsers, such as used to compile TypeScript
  • WebPack: module packager, its main function is packaging and compression , merge and load in sequence

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

2.3. The three ends are the same

The main purpose of hybrid development(Hybrid App)

is to realize a set of three-end unified code (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
  • Local packaging: Cordova (formerly PhoneGap)

WeChat Mini Program

For details, please see the WeChat official website. Here is a framework that facilitates WeChat Mini Program UI development: WeUI

2.4, Back-end technology

Front-end personnel also need to master certain back-end technologies in order to facilitate development. However, our Java back-end personnel know that the back-end knowledge system is extremely large and complex, so in order to facilitate front-end personnel to develop back-end applications, there is Technologies like Node JS. The author of Node JS has claimed to give up Node JS (saying that the architecture is not well done and the heavy node modules may make the author unhappy) and started to develop a new architecture of De no
. Since it is a background technology, it must be Frameworks and project management tools are required. The Node JS framework and project management tools are as follows:

  • Express: Node JS Framework
  • Koa: Express simplified version
  • NPM: Project Comprehensive management tool, similar to Maven
  • YARN: 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. It has many practical basic components that are richer than those of element ui. It mainly serves PC interfaces. Mid- and back-end products. The Vue component development model using a single file is developed based on npm webpack babel, supports ES 2015 high-quality, feature-rich and friendly API, and uses space freely and flexibly.

  • Official website address
  • Github
  • iview-admin

Note: It belongs to the mainstream front-end framework and can be selected when selecting Consider using it. The main feature is that the mobile terminal supports more

Element UI

Element is a Vue UI component library maintained by Ele.me’s front-end open source and has complete components. , basically covers all the components required by the backend, the documentation is explained in detail, and the examples are also abundant. Mainly used for developing PC-side pages, it is a relatively high-quality Vue UI component library.
·Official website address
·Git hub
·vue-element-admin
Note: It belongs to the mainstream front-end framework and can be considered when selecting. The main feature is that it has more desktop support

ICE

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

  • Official website address.

  • Git hub

Note: The main components are still based on React. As of February 17, 2019, the support for Vue is not yet complete 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. It provides a complete set of UI basic components and business components. Through Vant, you can quickly build a page with a unified style and improve development efficiency.

  • Official website address
  • Github

AtUI

at-ui is a Vue 2. x's front-end UI component library, mainly used for rapid development of PC website products. It provides a set of npm webpack babel front-end development workflow, CSS style is independent, and a unified UI style can be maintained even if different frameworks are used.
·Official website address
·Git hub

Cube Ul

cube-ui is an exquisite mobile component based on Vue js developed by Didi team library. It supports on-demand introduction and post-compilation, is lightweight and flexible, has strong scalability, and can easily implement secondary development based on existing components.

  • Official website address
  • Github

Hybrid development

Flutter

Flutter is Google's mobile UI framework, which can build high-quality native applications on Android and iOS in a very short time. Flutter works with existing code, it is used by developers and organizations around the world, and Flutter is free and open source.

  • Official website address
  • Github
    Remarks: Produced by Google, its main feature is to quickly build native APP applications. If you are doing hybrid applications, this framework is a must-have 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 its use a common choice for web and mobile developers.

  • Official website address

·Official website document
·Git hub

WeChat applet

mpvue

mpvue is a front-end framework developed by Meituan using Vue.js to develop mini programs. It currently supports WeChat mini programs, Baidu smart mini programs, and Toutiao mini programs. program and Alipay applet. The framework is based on Vue.js, and the modified runtime framework runtime and code compiler compiler are implemented so that it can run in a small program environment, thus providing Mini program development introduces Vue.js development experience.
·Official website address
·Git hub
Remarks: Complete Vue development experience, and supports multi-platform small program development, it is recommended to use

WeUI

WeUI is a set of basic style libraries that are consistent with WeChat’s native visual experience. It is tailor-made by WeChat’s official design team for WeChat web pages and WeChat mini-programs to make 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 and rear separation

Why front and rear separation is needed

3.1. Back-end-focused MVC era

In order to reduce the complexity of development, the back-end is the starting point. For example, the use of Struts, Spring MVC and other frameworks is the back-end MVC era;
With SpringMVC Process as an example:

  • Initiate a request to the front-end controller (Dispatcher Servlet)
  • Front-end controller requestHandlerMappingFindHandler, you can xmlConfiguration, annotation search
  • Processor mapperHandlerMappingReturn to front-end controllerHandler
  • Front-end controller Call the processor adapter to execute Handler
  • The processor adapter to executeHandler
  • ##HandlerReturn to the adapter after execution is completedModelAndView
  • The processor adapter returns
  • ModelAndView to the front-end controller. ModelAndView is an underlying object of the SpringMvc framework, including Model and View
  • The front-end controller requests the view parser to perform view parsing, and parses it into a real view according to the logical view name (
  • JSP )
  • The view resolver returns
  • View
  • to the front-end controller for view rendering, and the view rendering converts the model data (in the
  • ModelAndView object Medium) is filled into the request domain
  • The front-end controller responds to the user with the result

  • Advantages MVC is a very good collaboration model that can effectively reduce The coupling of code allows developers to understand where the code should be written architecturally. In order to make the View more pure, you can also use template engines such as Thyme leaf and Free marker to prevent Java code from being written in the template and make the division of labor between the front and back ends clearer.

    Disadvantages
  • 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 Write the DEMO on the front end. After writing it, let the back end apply the template. The advantage is that DEMO can be developed locally and is very efficient. The disadvantage is that the back-end needs to apply the template, which may be wrong. After the application is completed, it needs to be confirmed by the front-end, and the cost of back-and-forth communication and adjustment is relatively high;
    • Another collaboration model is that the front-end is responsible for all development and development of the browser side. Server-side View layer template development. The advantage is that UI-related codes can be written on the front end, and you don’t need to pay too much attention to the back end. The disadvantage is that front-end development is heavily bound to the back-end environment, and the environment has become 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 can still implement various business logic through the context variables it obtains. In this way, as long as the front-end is weak, the back-end will often be required 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 about by the front-end, but they are. Implemented by the backend. The Controller itself and the Model are often entangled, and the business code that makes people grit their teeth often appears in the Controller layer. These problems cannot all be attributed to the quality of programmers, otherwise JSP will be enough.
  • Limitations on the front-end: If performance optimization is done only on the front-end, the space is very limited, so we often need back-end cooperation. However, due to the limitations of the back-end framework, it is difficult for us to use [Comet] and [Big Pipe] ] and other technical solutions to optimize performance.

  • Note: During this period (before 2005), including early JSP and PHP, it can be called the Web 1.0 era. I want to say something here, if you are a Java beginner, please stop taking some old technologies seriously, such as JSP, because times are changing, technology is changing, and everything is changing (quoting Zuckerberg (A famous saying: the only constant is change itself); when we go to the university for practical training, some students will think that we don’t talk about any useful information. In fact, this is not the case. It can only be said that the useful information in your cognition is good for the market. It’s just that it has been outdated for a long time
3.2. The SPA era based on AJAX

The time goes back to 2005 A OAX (Asynchronous JavaScript And XML, asynchronous JavaScript and XML , old technology, new usage) was officially proposed and CDN began to be used as static resource storage, so the return of the king of JavaScript appeared (before this, JS was used to post dog skin plaster advertisements on web pages) SPA (Single Page Application) single page application era.



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 wonderful, but looking back, it's not much 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,
In this era, the layered architecture on the browser side has begun to appear:
Disadvantages

  • Conventions on front-end and back-end interfaces: If the back-end interface is 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, through interface rules, Interface platform and other methods to do it. With the interface rules precipitated together with the back-end, it can also be used to simulate data, so that the front-end and back-end can achieve efficient parallel development after agreeing on the interface.
  • Complexity control of front-end development: SPA applications are mostly functional and interactive, and it is normal for JavaScript code to exceed 100,000 lines. The organization of a large amount of JS code, binding to the View layer, etc. are not easy tasks.

3.3. Front-end-based MV* era

The MV* model here is as follows:

  • MVC (mainly synchronous communication): Model , View, Controller
  • MVP (mainly asynchronous communication): Model, View, Presenter
  • MVVM (mainly asynchronous communication): Model, View, 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. These frameworks generally The principle is to first layer by type, such as Templates, Controllers, and Models, and then segment within the layers, as shown below:

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, the simulation of test data is not difficult, and the front end can be developed locally. The backend can focus on processing business logic and output RESTful and other interfaces.
  • The complexity of front-end development is controllable: The front-end code is heavy, but reasonable layering allows the front-end code to perform its duties. This is quite interesting, as simple as the selection of template features, there are many details to pay attention to. The more powerful the better, what are the restrictions, what freedoms are left, how the code should be organized, all this design, it would take a book to explain.
  • Deployment is relatively independent: Can quickly improve product experience 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 back-end data verification can be relatively simple.
  • Fully asynchronous, bad for SEO. It is often necessary to implement a downgrade solution for synchronous rendering on the server side.
  • The performance is not the best, 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 cannot be fully controlled by the frontend.

3.4. The full-stack era brought by Node JS

The front-end-focused MV* model has solved many, many problems, but as mentioned above, there are still many shortcomings. . With the rise of Node JS, JavaScript has begun to have 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 clear. For the front end, the two UI layers perform their respective duties:

  • Front-end Ul layer handles the display logic of the browser layer. Render styles through CSS, add interactive functions through JavaScript, and HTML generation can also be placed in 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 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 its strong focus on presentation and can instead focus on the development of the business logic layer.
    Through Node, the WebServer layer is also JavaScript code, which means that some codes can be reused before and after. Scenes that require SEO can be rendered synchronously on the server side. Performance problems caused by too many asynchronous requests can also be alleviated by the server side. The shortcomings of the former 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 return to the original development model, but it is a spiral return.
    The full-stack model based on Node JS still faces many challenges:
  • The front-end needs to have a better understanding of server-side programming. For example, mastery of network knowledge such as TCP/IP.
  • Efficient communication between Node JS layer and Java layer. In Node JS mode, everything is on the server side. RESTful HTTP communication may not be efficient. Communication through SOAP and other methods is more efficient. Everything needs to be verified.
  • Proficient understanding of the department and operation and maintenance levels requires more knowledge points and practical experience.
  • How to transition a large number of historical issues. This is probably the biggest obstacle.
    Note: After seeing this, I believe many students can understand why I always say in class: "It is difficult for the front-end to learn the back-end, but it is easy for us back-end programmers to learn anything"; that is Because our back-end programmers have a relatively complete knowledge system.
    Full stack! So Easy!

3.5. Summary

In summary, whether it is a model or a technology, there is no good or bad distinction. Only whether it is suitable or not is suitable; the development idea of ​​front-end and back-end separation is mainly based on Soc (principle of separation of concerns). The above models all make the responsibilities of the front-end and back-end 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 developed by Microsoft WPF (using Developed by architects Ken Cooper and Ted Peters to replace WinForm, which was used to develop desktop applications in the past) and Silverlight (similar to Java Applet, to put it simply, it runs WPF on the browser), it is a simplified user interface The event-driven programming approach. Published by John Gossman (also the 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 converting data objects in the Model to make the data easier to manage and use. Its function is as follows:

  • This layer performs two-way data binding with the view layer upwards
  • It interacts with the Model layer through interface requests downwards

MVVM is quite mature and is mainly used but not only in network application development. The popular MVVM frameworks currently include Vue.js, Anfular JS

4.2. Why should we use MVVM

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

  • Low coupling: The view (View) can change and modify independently of the Model, and a ViewModel can Bound to different Views, the Model can remain unchanged when the View changes, and the View can remain unchanged when the Model changes.
  • Reusable: You can put some view logic in a ViewModel and let many Views reuse this view logic.
  • Independent development: Developers can focus on the development of business logic and data (ViewMode), and designers can focus on page design.
  • Testable: The interface has always been difficult to test, but now tests can be written for ViewModel.

(1) View

View is the view layer, which is the user interface. The front-end is mainly built by HTH L and csS. In order to more conveniently display the data of vi eu to del or hodel layer, various front-end and back-end template languages ​​​​have been produced, such as FreeMarker, Thyme leaf, etc., major MV VM Frameworks such as Vue.js, Angular JS, EJS, etc. also have their own built-in template 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 on the back end, mainly around the database system. The difficulty here mainly lies in the need to agree on unified interface rules with the front end

(3) ViewModel

ViewModel is the view data layer generated and maintained by the front-end developer organization. At this layer, the front-end developer converts the Model data obtained from the back-end and performs secondary encapsulation 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 the state and behavior of the view, while the data model of the Model layer only contains the state

  • For example, this part of the page is displayed What, what is displayed in that area, these all belong to view state (display)
  • What happens when the page is loaded, what happens when this area is clicked, what happens when this area is scrolled, these all belong to view behavior (interaction)

View state and behavior are encapsulated in the View Model. This kind of encapsulation allows the View Model to completely describe the View layer. Due to the implementation 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 inefficiently and troublesomely update the view by manipulating the DOM.
 The MVVM framework has already taken care of the dirtiest and most tiring part. We developers only need to process and maintain the View Model. When the data view is updated, it will automatically be 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. , This completely decouples the View layer and the Model layer. This decoupling is crucial. It is an important part of the implementation of the front-end and back-end separation solution.

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 get started, but also easy to integrate with third-party libraries (such as vue-router, vue-resource, vue x) or existing projects.

(1) Implementer of MVVM pattern

  • Model: Model layer, here represents JavaScript object
  • View: View layer, Here it represents the DOM (the element of HTML operation)
  • ViewModel: the middleware that connects the view and the data. Vue.js is the implementer of the View Model layer in MVVM

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

  • ViewModel can observe changes in data and monitor the view. Update the corresponding content
  • ViewModel can monitor changes in the view and notify data of changes

At this point, we understand that Vue.js is an implementation of MV VM Or, its core is to implement DOM monitoring and data binding

(2) Why use Vue.js

  • Lightweight and small size is an important indicator. Vue.js is only over 20kb after compression (Angular is 56kb after compression, React is 44kb after compression)
  • Mobile first. More suitable for the mobile terminal, such as the Touch event on the mobile terminal
  • Easy to use, smooth learning curve, complete documentation
  • Absorbs the strengths of Angular (modularity) and React (virtual DOM), and has its own Unique features, such as: calculated properties
  • Open source, high community activity

4.4, the first Vue program

[Explanation] IDEA can install Vue Plug-in!
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 compatible browsers.

(1) Download address

  • Development version
    • Contains complete warning and debug modes: https://yuejs.org/ js/vue.js
    • Removed warning, 30.96KB min gzip: https://vuejs.org/js/vue.min.js
  • CDN
    • <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>
    • <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>

(2) Code writing

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

nbsp;html>
    <meta>
    <title>Title</title>

2. Introduce Vue .js

<!--1.导入Vue.js--><script></script>12

3. Create a Vue instance

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

Instructions:

  • ##el: '#vue ': The ID of the bound element
  • data:{message:'Hello Vue!'}: There is a property named message in the data object, and the initial value is set Hello Vue!
4. Bind data to page elements

<!--view层,模板--><p>
    {{message}}</p>
Instructions: Just use double curly braces to wrap the message attribute created by Vue in the bound element. The data binding function can be realized, and the effect required by the View Model layer can be achieved. Is it very similar to the EL expression?

(3) Complete HTML

nbsp;html>
    <meta>
    <title>Title</title><!--view层,模板--><p>
    {{message}}</p><script></script><script>
    var vm = new Vue({
        el:"#app",
        /*Model:数据*/
        data:{
            message:"hello,vue!"
        }
    });</script>

(4)Test

为了能够更直观的体验Vue带来的数据绑定功能, 我们需要在浏览器测试一番, 操作流程如下:
  1、在浏览器上运行第一个Vue应用程序, 进入开发者工具
  2、在控制台输入vm.message=‘HelloWorld’, 然后回车, 你会发现浏览器中显示的内容会直接变成HelloWorld
  此时就可以在控制台直接输入vm.message来修改值, 中间是可以省略data的, 在这个操作中, 我并没有主动操作DOM, 就让页面的内容发生了变化, 这就是借助了Vue的数据绑定功能实现的; MV VM模式中要求View Model层就是使用观察者模式来实现数据的监听与绑定, 以做到数据与视图的快速响应。

五、基础语法指令

4.1、v-bind

我们已经成功创建了第一个Vue应用!看起来这跟渲染一个字符串模板非常类似, 但是Vue在背后做了大量工作。现在数据和DOM已经被建立了关联, 所有东西都是响应式的。我们在控制台操作对象属性,界面可以实时更新!
  我们还可以使用v-bind来绑定元素特性!
  上代码

nbsp;html>
    <meta>
    <title>Title</title>

         鼠标悬停几秒钟查看此处动态绑定的提示信息!  

<script></script><script> var vm = new Vue({ el:"#app", /*Model:数据*/ data:{ message: &#39;页面加载于 &#39; + new Date().toLocaleString() } });</script>

你看到的v-bind等被称为指令。指令带有前缀v以表示它们是Vue提供的特殊特性。可能你已经猜到了, 它们会在渲染的DOM上应用特殊的响应式行为在这里,该指令的意思是:“将这个元素节点的title特性和Vue实例的message属性保持一致”。
  如果你再次打开浏览器的JavaScript控制台, 输入app, message=‘新消息’,就会再一次看到这个绑定了title特性的HTML已经进行了更新。

4.2、v-if, v-else

什么是条件判断语句,就不需要我说明了吧,以下两个属性!

  • v-if
  • v-else

上代码

nbsp;html>
    <meta>
    <title>Title</title><p>
    </p>

Yes

    

No

   <script></script><script> var vm = new Vue({ el:"#app", /*Model:数据*/ data:{ type: true } });</script>

测试:
1.在浏览器上运行,打开控制台!
2.在控制台输入vm.ok=false然后回车,你会发现浏览器中显示的内容会直接变成NO
  注:使用v-*属性绑定数据是不需要双花括号包裹的

v-else-if

  • v-if
  • v-else-if
  • v-else
    注:===三个等号在JS中表示绝对等于(就是数据与类型都要相等)上代码:
nbsp;html>
    <meta>
    <title>Title</title><p>
    </p>

A

    

B

    

D

    

C

<script></script><script> var vm = new Vue({ el:"#app", /*Model:数据*/ data:{ type: &#39;A&#39; } });</script>

4.3、v-for

  • v-for

格式说明

<p>
    </p>
  •         {{item.message}}---{{index}}    
  • 123456

    注:items是数组,item是数组元素迭代的别名。我们之后学习的Thymeleaf模板引擎的语法和这个十分的相似!
      上代码:

    nbsp;html>
        <meta>
        <title>Title</title><p>
        </p>
  •         {{item.message}}---{{index}}    
  • <script></script><script> var vm = new Vue({ el:"#app", /*Model:数据*/ data:{ items:[ {message:&#39;狂神说Java&#39;}, {message:&#39;狂神说前端&#39;}, {message:&#39;狂神说运维&#39;} ] } });</script>

    测试:在控制台输入vm.items.push({message:'狂神说运维'}),尝试追加一条数据,你会发现浏览器中显示的内容会增加一条狂神说运维.

    4.4、v-on

    v-on监听事件
     emsp;事件有Vue的事件、和前端页面本身的一些事件!我们这里的click是vue的事件, 可以绑定到Vue中的methods中的方法事件!
      上代码

    nbsp;html>
        <meta>
        <title>Title</title>

        

    <script></script><script> var vm = new Vue({ el:"#app", data:{ message:&#39;Hello World&#39; }, methods:{ sayHi:function(event){ //&#39;this&#39;在方法里面指向当前Vue实例 alert(this.message); } } });</script>

    点击测试
      Vue还有一些基本的使用方式, 大家有需要的可以再跟着官方文档看看, 因为这些基本的指令几乎我们都见过了,一通百通!掌握学习的方式!

    六、表单双绑、组件

    6.1、什么是双向数据绑定

    Vue.js是一个MV VM框架, 即数据双向绑定, 即当数据发生变化的时候, 视图也就发生变化, 当视图发生变化的时候,数据也会跟着同步变化。这也算是Vue.js的精髓之处了。
      值得注意的是,我们所说的数据双向绑定,一定是对于UI控件来说的非UI控件不会涉及到数据双向绑定。单向数据绑定是使用状态管理工具的前提。如果我们使用vue x那么数据流也是单项的,这时就会和双向数据绑定有冲突。

    (1)为什么要实现数据的双向绑定

    Vue.js中,如果使用vuex, 实际上数据还是单向的, 之所以说是数据双向绑定,这是用的UI控件来说, 对于我们处理表单, Vue.js的双向数据绑定用起来就特别舒服了。即两者并不互斥,在全局性数据流使用单项,方便跟踪;局部性数据流使用双向,简单易操作。

    6.2、在表单中使用双向数据绑定

    你可以用v-model指令在表单、及元素上创建双向数据绑定。它会根据控件类型自动选取正确的方法来更新元素。尽管有些神奇, 但v-model本质上不过是语法糖。它负责监听用户的输入事件以更新数据,并对一些极端场景进行一些特殊处理。
      注意:v-model会忽略所有表单元素的valuecheckedselected特性的初始值而总是将Vue实例的数据作为数据来源。你应该通过JavaScript在组件的data选项中声明初始值!

    (1)单行文本

    nbsp;html>
        <meta>
        <title>Title</title>

        输入的文本:{{message}}

    <script></script><script> var vm = new Vue({ el:"#app", data:{ message:"" } });</script>

    (2)多行文本

    nbsp;html>
        <meta>
        <title>Title</title>

       多行文本:  多行文本是:{{pan}}

    <script></script><script> var vm = new Vue({ el:"#app", data:{ message:"Hello hello!" } });</script>

    (3)单复选框

    nbsp;html>
        <meta>
        <title>Title</title>

        单复选框:                

    <script></script><script> var vm = new Vue({ el:"#app", data:{ checked:false } });</script>

    4多复选框

    nbsp;html>
        <meta>
        <title>Title</title>

        多复选框:                                                       选中的值:{{checkedNames}}

    <script></script><script> var vm = new Vue({ el:"#app", data:{ checkedNames:[] } });</script>

    (6)单选按钮

    nbsp;html>
        <meta>
        <title>Title</title>

        单选框按钮                        选中的值:{{picked}}

    <script></script><script> var vm = new Vue({ el:"#app", data:{ picked:&#39;Two&#39; } });</script>

    (7)下拉框

    nbsp;html>
        <meta>
        <title>Title</title>

        下拉框:         value:{{pan}}

    <script></script><script> var vm = new Vue({ el:"#app", data:{ pan:"A" } });</script>

    注意:v-model表达式的初始值未能匹配任何选项,元系将被渲染为“未选中”状态。 在iOS中, 这会使用户无法选择第一个选项,因为这样的情况下,iOS不会触发change事件。因此,更推荐像上面这样提供一个值为空的禁用选项。

    6.3、什么是组件

    组件是可复用的Vue实例, 说白了就是一组可以重复使用的模板, 跟JSTL的自定义标签、Thymelealth:fragment等框架有着异曲同工之妙,通常一个应用会以一棵嵌套的组件树的形式来组织:

    例如,你可能会有页头、侧边栏、内容区等组件,每个组件又包含了其它的像导航链接、博文之类的组件。

    (1)第一个Vue组件

    注意:在实际开发中,我们并不会用以下方式开发组件,而是采用vue-cli创建,vue模板文件的方式开发,以下方法只是为了让大家理解什么是组件。
      使用Vue.component()方法注册组件,格式如下:

    <p>
      <pan></pan></p><script></script><script>
        //先注册组件
        Vue.component("pan",{
            
            template:&#39;<li>Hello&#39;
    
        });
        //再实例化Vue
        var vm = new Vue({
            el:"#app",
        });</script>

    说明:

    • Vue.component():注册组件
    • pan:自定义组件的名字
    • template:组件的模板

    (2)使用props属性传递参数

    像上面那样用组件没有任何意义,所以我们是需要传递参数到组件的,此时就需要使用props属性了!
      注意:默认规则下props属性里的值不能为大写;

    nbsp;html>
        <meta>
        <title>Title</title>

           

    <script></script><script> //定义组件 Vue.component("pan",{ props:[&#39;panh&#39;], template:&#39;<li>{{panh}}&#39; }); var vm = new Vue({ el:"#app", data:{ items:["java","Linux","前端"] } });</script>

    说明

    • v-for="item in items":遍历Vue实例中定义的名为items的数组,并创建同等数量的组件
    • v-bind:panh="item":将遍历的item项绑定到组件中props定义名为item属性上;= 号左边的panhprops定义的属性名,右边的为item in items 中遍历的item项的值

    七、Axios异步通信

    7.1、什么是Axios

    Axios是一个开源的可以用在浏览器端和Node JS的异步通信框架, 她的主要作用就是实现AJAX异步通信,其功能特点如下:

    • 从浏览器中创建XMLHttpRequests
    • 从node.js创建http请求
    • 支持Promise API[JS中链式编程]
    • 拦截请求和响应
    • 转换请求数据和响应数据
    • 取消请求
    • 自动转换JSON数据
    • 客户端支持防御XSRF(跨站请求伪造)

    GitHub:https://github.com/axios/axios
      中文文档:http://www.axios-js.com/

    7.2、为什么要使用Axios

    由于Vue.js是一个视图层框架并且作者(尤雨溪) 严格准守SoC(关注度分离原则)所以Vue.js并不包含AJAX的通信功能, 为了解决通信问题, 作者单独开发了一个名为vue-resource的插件, 不过在进入2.0版本以后停止了对该插件的维护并推荐了Axios框架。少用jQuery, 因为它操作Dom太频繁!

    7.3、第一个Axios应用程序

    咱们开发的接口大部分都是采用JSON格式, 可以先在项目里模拟一段JSON数据, 数据内容如下:创建一个名为data.json的文件并填入上面的内容, 放在项目的根目录下

    {
      "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/"
        }
      ]}

    测试代码

    nbsp;html>
        <meta>
        <title>Title</title>
        
        <p>
        </p>

    地名:{{info.name}}

        

    地址:{{info.address.country}}--{{info.address.city}}--{{info.address.street}}

        

    链接:{{info.url}} 

    <script></script><script></script><script> 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(&#39;data.json&#39;) .then(response=>(this.info=response.data)); } });</script>

    说明:

    1. 在这里使用了v-bind将a:href的属性值与Vue实例中的数据进行绑定
    2. 使用axios框架的get方法请求AJAX并自动将数据封装进了Vue实例的数据对象中
    3. 我们在data中的数据结构必须和Ajax响应回来的数据格式匹配!

    7.4、Vue的生命周期

    官方文档:https://cn.vuejs.org/v2/guide/instance.html#生命周期图示
      Vue实例有一个完整的生命周期,也就是从开始创建初女台化数据、编译模板、挂载DOM、渲染一更新一渲染、卸载等一系列过程,我们称这是Vue的生命周期。通俗说就是Vue实例从创建到销毁的过程,就是生命周期。
      在Vue的整个生命周期中,它提供了一系列的事件,可以让我们在事件触发时注册JS方法,可以让我们用自己注册的JS方法控制整个大局,在这些事件响应方法中的this直接指向的是Vue的实例。

    八、计算属性、内容分发、自定义事件

    1、什么是计算属性

    计算属性的重点突出在属性两个字上(属性是名词),首先它是个属性其次这个属性有计算的能力(计算是动词),这里的计算就是个函数:简单点说,它就是一个能够将计算结果缓存起来的属性(将行为转化成了静态的属性),仅此而已;可以想象为缓存!
      上代码

    nbsp;html>
        <meta>
        <title>Title</title><p>
        </p>

    currentTime1:{{currentTime1()}}

        

    currentTime2:{{currentTime2}}

    <script></script><script> 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>

    注意:methods和computed里的东西不能重名
    说明:

    • methods:定义方法, 调用方法使用currentTime1(), 需要带括号

    • computed:定义计算属性, 调用属性使用currentTime2, 不需要带括号:this.message是为了能够让currentTime2观察到数据变化而变化

    • 如何在方法中的值发生了变化,则缓存就会刷新!可以在控制台使用vm.message=”q in jiang", 改变下数据的值,再次测试观察效果!

      结论:
        调用方法时,每次都需要讲行计算,既然有计算过程则必定产生系统开销,那如果这个结果是不经常变化的呢?此时就可以考虑将这个结果缓存起来,采用计算属性可以很方便的做到这点,计算属性的主要特性就是为了将不经常变化的计算结果进行缓存,以节约我们的系统开销;

    8.2、内容分发

    Vue.js中我们使用<slot></slot>元素作为承载分发内容的出口,作者称其为插槽,可以应用在组合组件的场景中;

    测试

    比如准备制作一个待办事项组件(todo) , 该组件由待办标题(todo-title) 和待办内容(todo-items)组成,但这三个组件又是相互独立的,该如何操作呢?
      第一步定义一个待办事项的组件

    <p>
        <todo></todo></p><!--1.导入Vue.js--><script></script><script>
        Vue.component(&#39;todo&#39;,{
            template:&#39;<p>\
                    <p>代办事项\
                    <ul>\
                        <li>学习狂神说Java\
                    \
                &#39;
        })</script>

    第二步 我们需要让,代办事项的标题和值实现动态绑定,怎么做呢?我们可以留一个插槽!
      1-将上面的代码留出一个插槽,即slot

     Vue.component('todo',{
            template:'<p>\                <slot></slot>\                </p>
      \                    <slot></slot>\                
    \            '     });

    2-定义一个名为todo-title的待办标题组件 和 todo-items的待办内容组件

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

    3-实例化Vue并初始化数据

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

    4-将这些值,通过插槽插入

    <p>
        <todo>
            <todo-title></todo-title>
            <!--<todo-items slot="todo-items" v-for="{item,index} in todoItems" v-bind:item="item"></todo-items>-->
            <!--如下为简写-->
            <todo-items></todo-items>    </todo></p>

    说明:我们的todo-title和todo-items组件分别被分发到了todo组件的todo-title和todo-items插槽中
      完整代码如下:

    nbsp;html>
        <meta>
        <title>Title</title><p>
        <todo>
            <todo-title></todo-title>
            <!--<todo-items slot="todo-items" v-for="{item,index} in todoItems" v-bind:item="item"></todo-items>-->
            <!--如下为简写-->
            <todo-items></todo-items>    </todo></p><script></script><script>
        Vue.component(&#39;todo&#39;,{
            template:&#39;<p>\
                    <slot name="todo-title">\
                    <ul>\
                        <slot name="todo-items">\
                    \
                &#39;
        });
        Vue.component(&#39;todo-title&#39;,{
            props:[&#39;title&#39;],
            template:&#39;<p>{{title}}&#39;
        });
        //这里的index,就是数组的下标,使用for循环遍历的时候,可以循环出来!
        Vue.component("todo-items",{
            props:["item","index"],
            template:"<li>{{index+1}},{{item}}"
        });
    
        var vm = new Vue({
            el:"#vue",
            data:{
                title:"秦老师系列课程",
                todoItems:[&#39;test1&#39;,&#39;test2&#39;,&#39;test3&#39;]
            }
        });</script>

    8.3、自定义事件

    通以上代码不难发现,数据项在Vue的实例中, 但删除操作要在组件中完成, 那么组件如何才能删除Vue实例中的数据呢?此时就涉及到参数传递与事件分发了, Vue为我们提供了自定义事件的功能很好的帮助我们解决了这个问题; 使用this.$emit(‘自定义事件名’, 参数) , 操作过程如下:
      1-在vue的实例中增加了methods对象并定义了一个名为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-修改todo-items待办内容组件的代码,增加一个删除按钮,并且绑定事件!

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

    3-修改todo-items待办内容组件的HTML代码,增加一个自定义事件,比如叫remove,可以和组件的方法绑定,然后绑定到vue的方法!

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

    对上一个代码进行修改,实现删除功能

    nbsp;html>
        <meta>
        <title>Title</title>

                                                 

    <script></script><script> Vue.component(&#39;todo&#39;,{ template:&#39;<p>\ <slot name="todo-title">\ <ul>\ <slot name="todo-items">\ \ &#39; }); Vue.component(&#39;todo-title&#39;,{ props:[&#39;title&#39;], template:&#39;<p>{{title}}&#39; }); //这里的index,就是数组的下标,使用for循环遍历的时候,可以循环出来! Vue.component("todo-items",{ props:["item_p","index_p"], template:"<li>{{index_p+1}},{{item_p}} <button @click=&#39;remove_methods&#39;>删除", methods:{ remove_methods:function (index) { //this.$emit 自定义事件分发 this.$emit(&#39;remove&#39;,index); } } }); var vm = new Vue({ el:"#vue", data:{ title_text:"秦老师系列课程", todoItems:[&#39;test1&#39;,&#39;test2&#39;,&#39;test3&#39;] }, methods:{ removeItems:function(index){ console.log("删除了"+this.todoItems[index]+"OK"); this.todoItems.splice(index,1); } } });</script>

    逻辑理解

    8.4、Vue入门小结

    核心:数据驱动,组件化

    优点:借鉴了AngularJS的模块化开发和React的虚拟Dom,虚拟Dom就是把Demo操作放到内存中执行;

    常用的属性:

    • v-if
    • v-else-if
    • v-else
    • v-for
    • v-on绑定事件,简写@
    • v-model数据双向绑定
    • v-bind给组件绑定参数,简写:

    组件化:

    • 组合组件slot插槽
    • 组件内部绑定事件需要使用到this.$emit("事件名",参数);
    • 计算属性的特色,缓存计算数据

    遵循SoC关注度分离原则,Vue是纯粹的视图框架,并不包含,比如Ajax之类的通信功能,为了解决通信问题,我们需要使用Axios框架做异步通信;

    说明

    Vue的开发都是要基于NodeJS,实际开发采用Vue-cli脚手架开发,vue-router路由,vuex做状态管理;Vue UI,界面我们一般使用ElementUI(饿了么出品),或者ICE(阿里巴巴出品)来快速搭建前端项目~~

    官网:

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

    九、第一个vue-cli项目

    9.1、什么是vue-cli

    vue-cli官方提供的一个脚手架,用于快速生成一个vue的项目模板;
      预先定义好的目录结构及基础代码,就好比咱们在创建Maven项目时可以选择创建一个骨架项目,这个估计项目就是脚手架,我们的开发更加的快速;
      项目的功能

    • 统一的目录结构
    • 本地调试
    • 热部署
    • 单元测试
    • 集成打包上线

    9.2、需要的环境

    • Node.js:http://nodejs.cn/download/
      安装就是无脑的下一步就好,安装在自己的环境目录下
    • Git:https://git-scm.com/doenloads
      镜像:https://npm.taobao.org/mirrors/git-for-windows/

    确认nodejs安装成功:

    • cmd下输入node -v,查看是否能够正确打印出版本号即可!
    • cmd下输入npm -v,查看是否能够正确打印出版本号即可!
      这个npm,就是一个软件包管理工具,就和linux下的apt软件安装差不多!
        安装Node.js淘宝镜像加速器(cnpm)
        这样的话,下载会快很多~
    # -g 就是全局安装
    npm install cnpm -g
    
    # 或使用如下语句解决npm速度慢的问题
    npm install --registry=https://registry.npm.taobao.org

    安装的过程可能有点慢~,耐心等待!虽然安装了cnpm,但是尽量少用!
      安装的位置:C:\Users\administrator\AppData\Roaming\npm


      安装vue-cli

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

    9.3、第一个vue-cli应用程序

    1.创建一个Vue项目,我们随便建立一个空的文件夹在电脑上,我这里在D盘下新建一个目录

    D:\Project\vue-study;

    2.创建一个基于webpack模板的vue应用程序

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

    一路都选择no即可;
      说明:

    • Project name:项目名称,默认回车即可
    • Project description:项目描述,默认回车即可
    • Author:项目作者,默认回车即可
    • Install vue-router:是否安装vue-router,选择n不安装(后期需要再手动添加)
    • Use ESLint to lint your code:是否使用ESLint做代码检查,选择n不安装(后期需要再手动添加)
    • Set up unit tests:单元测试相关,选择n不安装(后期需要再手动添加)
    • Setupe2etests with Nightwatch:单元测试相关,选择n不安装(后期需要再手动添加)
    • Should we run npm install for you after the,project has been created:创建完成后直接初始化,选择n,我们手动执行;运行结果!

    (1)初始化并运行

    cd myvue
    npm install
    npm run dev

    执行完成后,目录多了很多依赖

    当出现问题时,可以查看提示进行处理如下

    十、webpack使用

    10.1、什么是Webpack

    本质上, webpack是一个现代JavaScript应用程序的静态模块打包器(module bundler) 。当webpack处理应用程序时, 它会递归地构建一个依赖关系图(dependency graph) , 其中包含应用程序需要的每个模块, 然后将所有这些模块打包成一个或多个bundle.
      Webpack是当下最热门的前端资源模块化管理和打包工具, 它可以将许多松散耦合的模块按照依赖和规则打包成符合生产环境部署的前端资源。还可以将按需加载的模块进行代码分离,等到实际需要时再异步加载。通过loader转换, 任何形式的资源都可以当做模块, 比如Commons JS、AMD、ES 6、CSS、JSON、Coffee Script、LESS等;
      伴随着移动互联网的大潮, 当今越来越多的网站已经从网页模式进化到了WebApp模式。它们运行在现代浏览器里, 使用HTML 5、CSS 3、ES 6等新的技术来开发丰富的功能, 网页已经不仅仅是完成浏览器的基本需求; WebApp通常是一个SPA(单页面应用) , 每一个视图通过异步的方式加载,这导致页面初始化和使用过程中会加载越来越多的JS代码,这给前端的开发流程和资源组织带来了巨大挑战。
      前端开发和其他开发工作的主要区别,首先是前端基于多语言、多层次的编码和组织工作,其次前端产品的交付是基于浏览器的,这些资源是通过增量加载的方式运行到浏览器端,如何在开发环境组织好这些碎片化的代码和资源,并且保证他们在浏览器端快速、优雅的加载和更新,就需要一个模块化系统,这个理想中的模块化系统是前端工程师多年来一直探索的难题。

    10.2、模块化的演进

    Script标签

    	<script></script>
    	<script></script>
    	<script></script>

    这是最原始的JavaScript文件加载方式,如果把每一个文件看做是一个模块,那么他们的接口通常是暴露在全局作用域下,也就是定义在window对象中,不同模块的调用都是一个作用域。
      这种原始的加载方式暴露了一些显而易见的弊端:

    • 全局作用域下容易造成变量冲突
    • 文件只能按照<script></script>的书写顺序进行加载
    • 开发人员必须主观解决模块和代码库的依赖关系
    • 在大型项目中各种资源难以管理,长期积累的问题导致代码库混乱不堪

    CommonsJS


    服务器端的NodeJS遵循CommonsJS规范,该规范核心思想是允许模块通过require方法来同步加载所需依赖的其它模块,然后通过exports或module.exports来导出需要暴露的接口。

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

    优点:

    • 服务器端模块便于重用
    • NPM中已经有超过45万个可以使用的模块包
    • 简单易用

    缺点:

    • 同步的模块加载方式不适合在浏览器环境中,同步意味着阻塞加载,浏览器资源是异步加载的
    • 不能非阻塞的并行加载多个模块

    实现:

    • 服务端的NodeJS
    • •Browserify,浏览器端的CommonsJS实现,可以使用NPM的模块,但是编译打包后的文件体积较大
    • modules-webmake,类似Browserify,但不如Browserify灵活
    • wreq,Browserify的前身

    AMD


    Asynchronous Module Definition规范其实主要一个主要接口define(id?,dependencies?,factory);它要在声明模块的时候指定所有的依赖dependencies,并且还要当做形参传到factory中,对于依赖的模块提前执行。

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

    优点

    • 适合在浏览器环境中异步加载模块
    • 可以并行加载多个模块

    缺点

    • 提高了开发成本,代码的阅读和书写比较困难,模块定义方式的语义不畅
    • 不符合通用的模块化思维方式,是一种妥协的实现

    实现

    • RequireJS
    • curl

    CMD


    Commons Module Definition规范和AMD很相似,尽保持简单,并与CommonsJS和NodeJS的Modules规范保持了很大的兼容性。

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

    优点:

    • 依赖就近,延迟执行
    • 可以很容易在NodeJS中运行缺点
    • 依赖SPM打包,模块的加载逻辑偏重

    实现

    • Sea.js
    • coolie

    ES6模块


    EcmaScript 6标准增加了JavaScript语言层面的模块体系定义。ES 6模块的设计思想, 是尽量静态化, 使编译时就能确定模块的依赖关系, 以及输入和输出的变量。Commons JS和AMD模块,都只能在运行时确定这些东西。

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

    优点

    • 容易进行静态分析
    • 面向未来的Ecma Script标准

    缺点

    • 原生浏览器端还没有实现该标准
    • 全新的命令,新版的Node JS才支持

    实现

    • Babel

    大家期望的模块
      系统可以兼容多种模块风格, 尽量可以利用已有的代码, 不仅仅只是JavaScript模块化, 还有CSS、图片、字体等资源也需要模块化。

    10.3、安装Webpack

    WebPack是一款模块加载器兼打包工具, 它能把各种资源, 如JS、JSX、ES 6、SASS、LESS、图片等都作为模块来处理和使用。
      安装:

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

    测试安装成功

    • webpack -v
    • webpack-cli -v

    配置

    创建 webpack.config.js配置文件

    • entry:入口文件, 指定Web Pack用哪个文件作为项目的入口
    • output:输出, 指定WebPack把处理完成的文件放置到指定路径
    • module:模块, 用于处理各种类型的文件
    • plugins:插件, 如:热更新、代码重用等
    • resolve:设置路径指向
    • watch:监听, 用于设置文件改动后直接打包
    module.exports = {
    	entry:"",
    	output:{
    		path:"",
    		filename:""
    	},
    	module:{
    		loaders:[
    			{test:/\.js$/,;\loade:""}
    		]
    	},
    	plugins:{},
    	resolve:{},
    	watch:true}

    直接运行webpack命令打包

    10.4、使用webpack

    1. 创建项目
    2. 创建一个名为modules的目录,用于放置JS模块等资源文件
    3. 在modules下创建模块文件,如hello.js,用于编写JS模块相关代码
    	//暴露一个方法:sayHi
    	exports.sayHi = function(){
    		document.write("<p>Hello Webpack</p>");
    	}
    1. 在modules下创建一个名为main.js的入口文件,用于打包时设置entry属性
    //require 导入一个模块,就可以调用这个模块中的方法了var hello = require("./hello");hello.sayHi();
    1. 在项目目录下创建webpack.config.js配置文件,使用webpack命令打包
    module.exports = {
    	entry:"./modules/main.js",
    	output:{
    		filename:"./js/bundle.js"
    	}}
    1. 在项目目录下创建HTML页面,如index.html,导入webpack打包后的JS文件
    	nbsp;html>
    	
    		
    			<meta>
    			<title>狂神说Java</title>
    		
    		
    			<script></script>
    		
    	
    1. 在IDEA控制台中直接执行webpack;如果失败的话,就使用管理员权限运行即可!
    2. 运行HTML看效果

    说明

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

    十一、vue-router路由

    11.1、说明


    学习的时候,尽量的打开官方的文档

    Vue Router是Vue.js官方的路由管理器。它和Vue.js的核心深度集成, 让构建单页面应用变得易如反掌。包含的功能有:

    • 嵌套的路由/视图表
    • 模块化的、基于组件的路由配置
    • 路由参数、查询、通配符
    • 基于Vue js过渡系统的视图过渡效果
    • 细粒度的导航控制
    • 带有自动激活的CSS class的链接
    • HTML5 历史模式或hash模式, 在IE 9中自动降级
    • 自定义的滚动行为

    11.2、安装

    基于第一个vue-cli进行测试学习; 先查看node modules中是否存在vue-router
      vue-router是一个插件包, 所以我们还是需要用n pm/cn pm来进行安装的。打开命令行工具,进入你的项目目录,输入下面命令。

    npm install vue-router --save-dev

    如果在一个模块化工程中使用它,必须要通过Vue.use()明确地安装路由功能:

    import Vue from 'vue'import VueRouter from 'vue-router'Vue.use(VueRouter);

    11.3、测试

    1、先删除没有用的东西
    2、components 目录下存放我们自己编写的组件
    3、定义一个Content.vue 的组件

    <template>
    	<p>
    		</p>
    <h1>内容页</h1>
    	</template><script>
    	export default {
    		name:"Content"
    	}</script>

    Main.vue组件

    	<template>
    	<p>
    		</p>
    <h1>首页</h1>
    	</template><script>
    	export default {
    		name:"Main"
    	}</script>

    4、安装路由,在src目录下,新建一个文件夹:router,专门存放路由,配置路由index.js,如下

    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、在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></app>'});

    6、在App.vue中使用路由

    <template>
    	<p>
    		<!--
    			router-link:默认会被渲染成一个<a>标签,to属性为指定链接
    			router-view:用于渲染路由匹配到的组件
    		-->
    		<router-link>首页</router-link>
    		<router-link>内容</router-link>
    		<router-view></router-view>
    	</p></template><script>
    	export default{
    		name:&#39;App&#39;
    	}</script><style></style>

    十二、实战快速上手

    我们采用实战教学模式并结合ElementUI组件库,将所需知识点应用到实际中,以最快速度带领大家掌握Vue的使用;

    12.1、创建工程

    注意:命令行都要使用管理员模式运行
    1、创建一个名为hello-vue的工程vue init webpack hello-vue
    2、安装依赖, 我们需要安装vue-router、element-ui、sass-loader和node-sass四个插件

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

    3、Npm命令解释:

    • npm install moduleName:安装模块到项目目录下
    • npm install -g moduleName:-g的意思是将模块安装到全局,具体安装到磁盘哪个位置要看npm config prefix的位置
    • npm install -save moduleName:–save的意思是将模块安装到项目目录下, 并在package文件的dependencies节点写入依赖,-S为该命令的缩写
    • npm install -save-dev moduleName:–save-dev的意思是将模块安装到项目目录下,并在package文件的devDependencies节点写入依赖,-D为该命令的缩写

    12.2、创建登录页面

    把没有用的初始化东西删掉!
      在源码目录中创建如下结构:

    • assets:用于存放资源文件
    • components:用于存放Vue功能组件
    • views:用于存放Vue视图组件
    • router:用于存放vue-router配置

    创建首页视图,在views目录下创建一个名为Main.vue的视图组件:

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

    创建登录页视图在views目录下创建名为Login.vue的视图组件,其中el-*的元素为ElementUI组件;

    <template>
      <p>
        <el-form>
          <h3>欢迎登录</h3>
          <el-form-item>
            <el-input></el-input>
          </el-form-item>
          <el-form-item>
            <el-input></el-input>
          </el-form-item>
          <el-form-item>
            <el-button>登录</el-button>
          </el-form-item>
        </el-form>
    
        <el-dialog>
          <span>请输入账号和密码</span>
          <span>
              <el-button>确定</el-button>
            </span>
        </el-dialog>
      </p></template><script>
        export default {
            name: "Login",
          data(){
              return{
                form:{
                  username:&#39;&#39;,
                  password:&#39;&#39;
                },
                //表单验证,需要在 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(&#39;/main&#39;);
                  }else{
                    this.dialogVisible=true;
                    return false;
                  }
                });
              }
          }
        }</script><style>
      .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>

    创建路由,在router目录下创建一个名为index.js的vue-router路由配置文件

    //导入vueimport 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: '/main',
          component: Main    },
        //首页
        {
          path: '/login',
          component: Login    },
      ]})

    APP.vue

    <template>
      <p>
        <router-view></router-view>
      </p></template><script>export default {
      name: &#39;App&#39;,}</script><style>#app {
      font-family: &#39;Avenir&#39;, 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)})

    测试:在浏览器打开 http://localhost:8080/#/login
    如果出现错误: 可能是因为sass-loader的版本过高导致的编译错误,当前最高版本是8.0.2,需要退回到7.3.1 ;
    去package.json文件里面的 "sass-loader"的版本更换成7.3.1,然后重新cnpm install就可以了;

    12.3、路由嵌套

    嵌套路由又称子路由,在实际应用中,通常由多层嵌套的组件组合而成。
    demo
    1、 创建用户信息组件,在 views/user 目录下创建一个名为 Profile.vue 的视图组件;
    Profile.vue

    <template>
      <h1>个人信息</h1></template><script>
      export default {
        name: "UserProfile"
      }</script><style></style>

    2、在用户列表组件在 views/user 目录下创建一个名为 List.vue 的视图组件;
    List.vue

    <template>
      <h1>用户列表</h1></template><script>
      export default {
        name: "UserList"
      }</script><style></style>

    3、 修改首页视图,我们修改 Main.vue 视图组件,此处使用了 ElementUI 布局容器组件,代码如下:
    Main.vue

    <template>
        <p>
          <el-container>
            <el-aside>
              <el-menu>
                <el-submenu>
                  <template><i></i>用户管理</template>
                  <el-menu-item-group>
                    <el-menu-item>
                    <!--插入的地方-->
                      <router-link>个人信息</router-link>
                    </el-menu-item>
                    <el-menu-item>
                    <!--插入的地方-->
                      <router-link>用户列表</router-link>
                    </el-menu-item>
                  </el-menu-item-group>
                </el-submenu>
                <el-submenu>
                  <template><i></i>内容管理</template>
                  <el-menu-item-group>
                    <el-menu-item>分类管理</el-menu-item>
                    <el-menu-item>内容列表</el-menu-item>
                  </el-menu-item-group>
                </el-submenu>
              </el-menu>
            </el-aside>
    
            <el-container>
              <el-header>
                <el-dropdown>
                  <i></i>
                  <el-dropdown-menu>
                    <el-dropdown-item>个人信息</el-dropdown-item>
                    <el-dropdown-item>退出登录</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-header>
              <el-main>
              <!--在这里展示视图-->
                <router-view></router-view>
              </el-main>
            </el-container>
          </el-container>
        </p></template><script>
        export default {
            name: "Main"
        }</script><style>
      .el-header {
        background-color: #B3C0D1;
        color: #333;
        line-height: 60px;
      }
      .el-aside {
        color: #333;
      }</style>

    4、 配置嵌套路由修改 router 目录下的 index.js 路由配置文件,使用children放入main中写入子模块,代码如下
    index.js

    //导入vueimport Vue from 'vue';import VueRouter 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(VueRouter);//导出export default new VueRouter({
      routes: [
        {
          //登录页
          path: '/main',
          component: Main,
          //  写入子模块
          children: [
            {
              path: '/user/profile',
              component: UserProfile,
            }, {
              path: '/user/list',
              component: UserList,
            },
          ]
        },
        //首页
        {
          path: '/login',
          component: Login    },
      ]})

    5、 路由嵌套实战效果图

    图 路由嵌套效果图

    12.4、参数传递

    这里演示如果请求带有参数该怎么传递
    demo
     用的还是上述例子的代码 修改一些代码 这里不放重复的代码了
    第一种取值方式
    1、 修改路由配置, 主要是router下的index.js中的 path 属性中增加了 :id 这样的占位符

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

    2、传递参数
     此时我们在Main.vue中的route-link位置处 to 改为了 :to,是为了将这一属性当成对象使用,注意 router-link 中的 name 属性名称 一定要和 路由中的 name 属性名称 匹配,因为这样 Vue 才能找到对应的路由路径;

    <!--name是组件的名字 params是传的参数 如果要传参数的话就需要用v:bind:来绑定--><router-link>个人信息</router-link>

    3、在要展示的组件Profile.vue中接收参数 使用 {{$route.params.id}}来接收
    Profile.vue 部分代码

    第二种取值方式 使用props 减少耦合
    1、修改路由配置 , 主要在router下的index.js中的路由属性中增加了 props: true 属性

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

    2、传递参数和之前一样 在Main.vue中修改route-link地址

    <!--name是组件的名字 params是传的参数 如果要传参数的话就需要用v:bind:来绑定--><router-link>个人信息</router-link>

    3、在Profile.vue接收参数为目标组件增加 props 属性
    Profile.vue

    <template>
      <p>
        个人信息
        {{ id }}  </p></template><script>
        export default {
          props: [&#39;id&#39;],
          name: "UserProfile"
        }</script><style></style>

    图 传参效果图

    12.5、组件重定向

    重定向的意思大家都明白,但 Vue 中的重定向是作用在路径不同但组件相同的情况下,比如:
    在router下面index.js的配置

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

    说明:这里定义了两个路径,一个是 /main ,一个是 /goHome,其中 /goHome 重定向到了 /main 路径,由此可以看出重定向不需要定义组件;

    使用的话,只需要在Main.vue设置对应路径即可;

    <el-menu-item>
        <router-link>回到首页</router-link></el-menu-item>

    12.6、路由模式与 404

    路由模式有两种

    • hash:路径带 # 符号,如 http://localhost/#/login
    • history:路径不带 # 符号,如 http://localhost/login

    修改路由配置,代码如下:

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

    404 demo
    1.创建一个NotFound.vue视图组件
    NotFound.vue

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

    2.修改路由配置index.js

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

    3.效果图

    图 404效果图

    路由钩子与异步请求

    beforeRouteEnter:在进入路由前执行
    beforeRouteLeave:在离开路由前执行

    在Profile.vue中写

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

    参数说明:
    to:路由将要跳转的路径信息
    from:路径跳转前的路径信息
    next:路由的控制参数
    next() 跳入下一个页面
    next(’/path’) 改变路由的跳转方向,使其跳到另一个路由
    next(false) 返回原来的页面
    next((vm)=>{}) 仅在 beforeRouteEnter 中可用,vm 是组件实例

    在钩子函数中使用异步请求

    1、安装 Axios

    cnpm install --save vue-axios

    2、main.js引用 Axios

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

    3、准备数据 : 只有我们的 static 目录下的文件是可以被访问到的,所以我们就把静态文件放入该目录下。
    数据和之前用的json数据一样 需要的去上述axios例子里

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

    4.在 beforeRouteEnter 中进行异步请求
    Profile.vue

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

    5.路由钩子和axios结合图

    更多编程相关知识,请访问:编程入门!!

    The above is the detailed content of Vue’s most detailed knowledge and notes. For more information, please follow other related articles on the PHP Chinese website!

    Statement:
    This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete