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

HTML + CSS + JS: View: refresh the data provided by the background

Network communication: Axios

Switch to vue-router

Status management: VUEX

Vue-ui: ICE, Element UI

I. Overview of VUE

Vue (pronounced /vju/, similar to View) is a set of progressive frameworks 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, which focuses only on the view layer, is not only easy to get started, but also easy to integrate with third-party libraries (such as VUe-Router: jump, VuE-Resource: communication, vuex: management) or existing projects.

Second, front-end core knowledge analysis

1. Front end three elements

  • HTML(Structural layer)Hyper Text Markup Language determines the structure and content of a web page
  • CSS(Performance layer)Cascading Style Sheets to Style your web page
  • JavaScript(Behavior layer): is a weakly typed scripting language in which the source code is interpreted by the browser rather than compiled to control the behavior of web pages

1.1 The CSS preprocessor does

  • SASS: Ruby based, server-side processing, powerful. Analyze the efficiency draft. You need to learn Ruby, which is more difficult than LESS.
  • LESS: Based on NodeJS, through the client processing, easy to use. The function is simpler than SASS and the parsing efficiency is lower than SASSThis is sufficient in real development, so backend people recommend using LESS if needed.

1.2 Native JS development

Native JS development, which lets us develop in ECMAScript standard, ES for short, is supported by all browsers. As of this blog post, the ES standard has been released in the following versions:

  • ES3

  • ES4 (Internal, not officially released)

  • ES5 (full browser support)

  • ES6 (common, current mainstream version: WebPack as ES5 support!)

  • ES7

  • ES8

  • ES9 (Draft stage)

The difference is the gradual addition of new features.

1.3 TypeScript Microsoft standard

TypeScript is a free and open source programming language developed by Microsoft. It is a superset of JavaScript, and essentially adds optional static typing and class-based object-oriented programming to the language. Founded by Anders Hejlsberg (father of C#, Delphi, TypeScript; .net founder).

The feature of the language is that in addition to the features of ES, there are many new features that are not included in the standard. As a result, many browsers do not support TypeScript syntax directly and need to compile (into JS) to be executed correctly by browsers.

2. JavaScript framework

The three front-end frameworks are Angular, React, and Vue

  • JQuery is a well-known JavaScript framework. Its advantage is that it simplifies DOM operations, but its disadvantage is that DOM operations are too frequent, which affects front-end performance. It is used in the front eye only for compatibility with IE6, 7, and 8.
  • Angular: A front-end framework acquired by Google, developed by a group of Java programmers, whoseThe feature is to move the MVC pattern from the background to the front and add the concept of modular development, working with Microsoft to develop in TypeScript syntax; Friendly to backend programmers, not so friendly to front-end programmers; The biggest disadvantage is that the version iteration is not reasonable (such as: 1 generation -> 2 generation, in addition to the name, is basically two things; Angular6 has been launched as of this blog).
  • React: Facebook, a high-performance JS front-end framework;A new concept [virtual DOM] is proposed to reduce real DOM operations and simulate DOM operations in memory, which effectively improves front-end rendering efficiency; The downside is complexity, as you need to learn an additional [JSX] language.
  • Vue: a JavaScript framework that is incremental. Incremental means implementing new features gradually, such as modular development, routing, state management, etc. It combines the advantages of Angular (modularity) and React (virtual DOM). .
  • Axios: Front-end communication framework; Since the boundary of Vue is very clear and it is designed to process DOM, it does not have communication capability, so it needs to use an additional communication framework to interact with the server. You can also choose to use the AJAX communication functionality provided by jQuery.

3. The UI framework

  • Ant-design: A React based UI framework developed by Alibaba
  • ElementUI, IView, ICE: UI framework based on Vue
  • Bootstrap: A Twitter application for front-end development
  • AmazeUI: Also called “sister UI”, an HTML5 cross-screen front-end framework

4. JavaScript build tools

  • Babel: JS compilation tool for ES features not supported by browsers, such as TypeScript compilation
  • WebPack: Module packer, the main function is to package, compress, merge and load in sequence

Front-end development mainly uses WebPack.

5. The three terminals are integrated

5.1 Mixed Development (Hybid App)

The main purpose is to realize the unification of three ends of a set of code (PC, Android:.APK, iOS:.IPA) and to be ready to call the underlying components (such as sensors, GPS, cameras, etc.). There are two main packaging methods:

  • HBuild -> HBuildX API Cloud
  • Native Packaging: Cordova (formerly PhoneGap)

5.2 wechat mini program

Please refer to the official website of wechat small program for details. Here is only a framework for convenient small program development:

  • WeUI

6. Back-end technology

Front-end personnel also need to master certain back-end technology in order to facilitate development, but we Java backend personnel know that the background knowledge system is extremely large and complex, so in order to facilitate front-end personnel to develop back-end applications, NodeJS technology emerged.

The authors of NodeJS have announced that they will scrap NodeJS and start working on a new Deno architecture

NodeJS framework and project management tools are as follows:

  • Express: NodeJS framework
  • Koa: Express lite
  • NPM: Integrated project management tool, similar to Maven
  • YARN: An alternative to NPM, similar to Maven and Gradle

7. Mainstream front-end frameworks

  • Vue.js

7.1 the iView

Iview is a powerful VUe-based UI library with many useful base components that are richer than those of ElementUI, primarily serving as a back-end product for PC interfaces. Using single file Vue component development mode based on NPM + Webpack + Babel development, support ES2015 high quality, rich and friendly API, free and flexible use of space.

  • The website address
  • Github
  • iview-admin

Note: It belongs to the mainstream front-end framework, which can be considered for selection. The main feature is that the mobile terminal supports more

7.2 ElementUI

Element is a Vue UI component library maintained by Ele. me front-end and open source. It has complete components and basically covers all the components required by the background. Mainly used to develop PC pages, is a relatively high quality Vue UI component library.

  • The website address
  • Making: vue – element – admin

Note: it belongs to the mainstream front-end framework, which can be considered for selection. The main feature is that the desktop side supports more

7.3 the ICE

Feibing is the alibaba team’s React/Angular/Vue application solution for the middle and background. Within Alibaba, there are already more than 270 projects from almost all BU in use. Feibing contains a complete link from the design end to the development end to help users quickly build their own background applications.

Note: React is still the main component. As of February 17, 2019, Vue support is not perfect, and it is still in the wait-and-see stage

7.4 VantUI

Vant UI is a Vue component library implemented by the uplike front-end team based on the uplike unified specification, providing a complete set of BASIC UI components and business components. With Vant, you can quickly build a unified style of the page, improve the efficiency of development.

7.5 AtUI

At-ui is a front-end UI component library based on Vue 2.x, which is mainly used for rapid development of PC website products. It provides a set of NPM + Webpack + Babel front-end development workflow, CSS style independence, even using different framework implementation can maintain a uniform UI style.

7.6 CubeUI

Cube-ui is a sophisticated mobile component library based on vue.js implemented by Didi team. Support on-demand introduction and post-compilation, lightweight and flexible; Strong scalability, can be easily based on existing components to achieve secondary development.

Mixed development

Flutter

Flutter is Google’s mobile UI framework for building Android and iOs in a very short time. High quality native apps. Flutter works with existing code, it is used by developers and organizations around the world, and Flutter is free and open source.

Note: Produced by Google, the main feature is the rapid construction of native APP applications, such as mixed applications, this framework is mandatory

lonic

Lonic is not only a CSS framework but also a Javascript UI library. Lonic is one of the most potential HTML5 mobile application development frameworks. Building applications with SASS provides many UI components to help developers develop powerful applications. It uses the JavaScript MVVM framework and AngularJS/Vue to enhance the application. Providing two-way binding of data has become a common choice for Web and mobile developers.

Wechat applets

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 intelligent small programs, Toutiao small programs and Alipay small programs. The framework is based on vue. js, modified runt ime and code compiler implementation, so that it can run in the small program environment, thus introducing vue. js development experience for small program development.

Note: Complete Vue development experience, and support multi-platform small program development, recommended use

WeUl

WeUI is a set of basic style library consistent with wechat’s native visual experience. It is designed by wechat’s official design team for wechat’s internal webpage and wechat mini program, so that users’ perception of use is more unified. Contains button, cell, Dialog, toast, article, icon and other elements.

3. Understand the evolutionary history of anterior and posterior end separation

1. Back-end oriented MVC era

In order to reduce the complexity of development, the starting point is the backend, such as the use of Struts, SpringMVC and other frameworks, is the backend MVC era;

Take the Spring MVC process as an example:

  • Initiate a request to the front-end controller (DispatcherServlet )
  • Front-end controller requestHandlerMappingTo find theHandler, can be based onxmlConfiguration, annotations to find
  • Processor mapperHandlerMappingThe forward controller returnsHandler
  • The front-end controller calls the processor adapter to execute the Handler
  • Processor adapter to executeHandler
  • HandlerReturn to adapter after executionModelAndView
  • The processor adapter returns to the forward controllerModelAndViewMode lAndViewSpringMVCAn underlying object of the framework, includingModelView
  • The front controller requests the view resolver to parse the view into a real view based on the logical view name (JSP )
  • The view resolver returns to the front controllerView
  • The front end controller renders the view, and the view renders the model data (inModelAndViewObject) torequest
  • The front-end controller responds to the user

advantages

  • MVC is a very good collaboration model that can reduce the coupling of code and let developers know architecturally where code should be written.
  • To make the View more pure, you can also use a template engine such as Thymeleaf and Freemarker to prevent Java code from being written into the template, making the front and back ends more clear.

disadvantages

  • Front-end development relies heavily on the development environment, resulting in low development efficiency. 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 then let the back end set the template. The advantage is that DEMO can be developed locally and is very efficient. The disadvantage is that the back-end template also needs to be set, which may be wrong. After the set, the front end needs to be determined, and the cost of communication and adjustment is relatively large.
    • Another collaboration is where the front end takes care of all development on the browser side and the View layer template development on the server side. The advantage is that the UI-related code is written in 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 the front end development.
  • Front end responsibility entanglements: | template bow with powerful function, still can get a context variable to realize all kinds of business logic. As a result, as long as the front end is weak, it is often required by the back end to write a lot of business code in the template layer. There’s also a big gray areaControllerPage routing and other functions that should be the front end’s primary concern are implemented by the back end.ControllerNothing to do withModelOften will be entangled, look at the teeth of the business code often appear inControllerLayer. These problems cannot all be attributed to programmer literacy, otherwise JSPS would be enough.
  • Limitations on the front end: performance optimization if only in the front end to do space is very limited, so we often need back-end cooperation, but because of the limitations of the back end framework, it is difficult to use ** [Comet] **, [BigPipe] and other technical solutions to optimize performance.

Note: During this period (prior to 2005), including the early days of JSP and PHP, you can call it the Web 1.0 era. Because times change, technology changes, everything changes.

In the words of Spencer Johnson, the world famous writer and great thinker: the only constant is change itself.

Some of the older technologies, such as JSP, are long out of date for the market.

2. SPA era brought by AJAX

Back in 2005, AJAX (Asynchronous JavaScript And XM, Asynchronous JavaScript And XML, old technology And new usage) was introduced And CDN was used for static resource storage. Thus came the return of JavaScript (until recently, JavaScript was used to advertise dog skin plaster on web pages) to the era of SPA (Single Page Application).

advantages

In this mode, the division of labor on the front and back ends is very clear, and the key collaborative point on the front and back ends is the AJAX interface. It looks great, but in retrospect, it’s not that different from the JSP era. The complexity has moved from JSPS on the server side to JavaScript on the browser side, where it becomes very complex. Like Spring MVC, this era began to see the emergence of browser-side layered architectures:

disadvantages

  • ** Front end interface conventions: ** If the back end interface is a mess, if the back end business model is not stable, then front-end development is a pain; Many teams are also trying to do this through interface rules, interface platforms, etc. With the interface rules deposited with the back end, it can also be used to simulate data, enabling the front and back ends to implement efficient parallel development after the interface is agreed.

  • ** Complexity control of front-end development: **SPA applications are mostly functionally interactive, and it is normal to have over 100,000 lines of JavaScript code. Organizing a lot of JS code, binding to the View layer, etc., are not easy things.

3 front-end dominated MV* era

The MV* mode is as follows:

  • MVC (mainly synchronous communication) : Model, View, Controller
  • MVP (asynchronous communication) : Model, View, Presenter
  • MVVM (mainly for asynchronous communication) : Model, View, ViewModel

In order to reduce the complexity of front-end development, a number of front-end frameworks have emerged, such as: AngularJS, React, Vue. Js, EmberJS, etc. The general principle of these frameworks is to first layer by type, such as Templates, Controllers, Models, and then slice within the layer.

advantages

  • The responsibilities of the front and back ends are clear: the front end works on the browser side and the back end works on the server side. Clear division of labor, can make development parallel, test data simulation is not difficult, front-end can be developed locally. The back end can focus on business logic processing, output RESTful interfaces.
  • ** The complexity of front-end development is manageable: ** The front-end code is heavy, but layered properly so that the front-end code does its job. This piece is quite interesting, as simple as the selection of template features, there are a lot of attention. What to limit, what to leave free, how the code should be organized, all of this is designed to take a book to explain.
  • ** Deployment is relatively independent: ** can quickly improve the product experience.

disadvantages

  • Code cannot be reused. For example, the back end still needs to do a variety of data verification, verification logic can not reuse the browser side of the code. If reusable, data validation on the back end can be relatively simple.

  • All asynchronous, bad for SEO. Often the server is also required to do a synchronous rendering degradation scheme.

  • Performance is not optimal, especially in the mobile Internet environment.

  • SPA can’t meet all needs, and there are still plenty of multi-page applications. URL Design requires the cooperation of the back end, and the front end cannot fully grasp it.

The full stack era of NodeJS agents

Front-end oriented MV* mode solves many problems, but as mentioned above, there are still many shortcomings. With the rise of NodeJS, JavaScript has become capable of running on the server side. This means there can be a new model of research and development:

In this mode of development, the responsibilities of the front and back end are clear. For the front end, there are two UI layers that do their job:

  • The Front-end UI Layer handles the presentation logic for the browser layer. CSS rendering styles, JavaScript interaction, and HTML generation can also be placed in this layer, depending on the application scenario.
  • The back-end UI Layer handles routing, templates, data retrieval, cookies, and more. Through routing, the front end can finally control URL Design, so that no matter it is a single page application or multi-page application, the front end can control freely. The back end can finally move away from a strong focus on presentation and focus on the business logic layer.

With Node, the Web Server layer is also JavaScript code, which means that parts of the code can be reused, SEO scenarios can be rendered synchronously on the Server side, and performance issues caused by too many asynchronous requests can be mitigated on the Server side. The deficiencies of the former model are almost perfectly solved by this model.

Compared to THE JSP pattern, the full-stack pattern looks like a regression, and it is a regression to the original development pattern, but in an upward spiral.

Nodejs-based full stack mode still faces many challenges:

  • You need the front end to have a better understanding of server-side programming. For example, TCP/IP and other network knowledge.
  • Efficient communication between NodeJS layer and Java layer. In NodeJS mode, RESTful HTTP communication may not be efficient on the server. SOAP communication is more efficient. – You need to go through validation.
  • A good understanding of deployment, operation and maintenance requires more knowledge points and practical experience.
  • How to transition a large number of issues left over from history. This is probably the biggest, biggest resistance.

Note: why it is said that “it is difficult for the front-end to learn the background while it is easy for us back-end programmers to learn anything”; Back-end programmers have a relatively complete body of knowledge.

5 concludes

To sum up, mode or technology, there is no good or bad, only suitable or not suitable; The development idea of the separation of front and rear is mainly based on SoC (separation of attention principle). All the above modes are to make the responsibilities of the front and rear end clearer, and the division of labor more reasonable and efficient.

Iv. MVVM mode

1 review the MVC

The MVC pattern represents the Model-View-Controller pattern.

This pattern is used for layered development of applications.

  • Model – A Model represents an object or JAVA POJO that accesses data. It can also have logic to update the controller as the data changes.
  • View – A View represents a visualization of the data contained in the model.
  • Controller (Controller) – Controllers act on models and views. It controls the flow of data to model objects and updates the view as the data changes. It separates the view from the model.

2 What is MVVM?

MVVM (Model-view-ViewModel) is a software architecture design pattern, developed by Microsoft WPF (used to replace WinForm, Ken Cooper and Ted Peters, architects of Silverlight (similar to Java applets, but simply WPF running in browsers), have previously used this technology to develop desktop applications, as an event-driven programming approach to simplifying user interfaces. Published by John Gossman (also WPF and Silverlight architect) on his blog in 2005.

MVVM is derived from the classic MVC (Modi-view-Controller) pattern.

The core of MVVM is the ViewModel layer, which is responsible for transforming data objects in Model to make data easier to manage and use. Its functions are as follows:

  • The layer goes up withViewLayer for bidirectional data binding
  • Down withModelThe layer interacts with data through interface requests

3 MVVM components

View

A View is the View layer, the user interface.

The front end is built with HTML and CSS, and a variety of front and back end template languages such as FreeMarker, Thymeleaf, etc., and MVVM frameworks such as Vue. Js have been developed to facilitate the presentation of ViewModel or Model layer data. AngularJS, EJS, and others also have their own built-in template languages for building user interfaces.

Model

Model is an exponential data Model, generally refers to the back-end of a variety of business logic processing and data manipulation, mainly around the database system.

The difficulty lies in the need for interface rules consistent with the front-end convention.

ViewModel

A ViewModel is a layer of view data generated and maintained by an organization of front-end developers. In this layer, the front-end developer transforms and encapsulates the Model data from the back end 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 ViewModel includes the state and behavior of the view, while the data Model of the Model layer only contains the state

  • So what’s on this part of the page, what’s on that part of the page these are all view states
  • What happens when the page loads in, what happens when you click on this piece, what happens when this piece scrolls these are all view behaviors

View state and behavior are encapsulated in the ViewModel. This encapsulation allows the ViewModel to fully describe the View layer. Because of the bidirectional binding, the ViewModel’s content is displayed in the View layer in real time, which is exciting because the front-end developer no longer has to make inefficient and cumbersome manipulation of the DOM to update the View.

The MVVM framework has already done the dirty and tiring part, we developers just need to process and maintain the ViewModel, update the data view will be automatically updated accordingly, truly achieve event-driven programming.

The View layer is not the Model layer data, but the ViewModel data, the ViewModel is responsible for the interaction with the Model layer, which 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 separation scheme.

4 Why use MVVM

The MVVM pattern, like the MVC pattern, primarily aims to separate views from models and has several benefits

  • Low coupling: Views can be changed and modified independently of Model. A ViewModel can be bound to different views, and 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 have many views reuse that View logic.
  • Independent development: Developers can focus on business logic and data development (ViewModel), and designers can focus on page design.
  • Testable: Interfaces are harder to test, and tests can now be written against the ViewModel.

5 MVVM framework

Popular MVVM frameworks include:

  • Vue.js
  • AngularJS

Vue is the implementor of the MVVM pattern

  • Model: Model layer, where JavaScript objects are represented
  • View: View layer, where DOM (element of HTML manipulation) is represented
  • ViewModelVue. Js is the implementer of the ViewModel layer in MVVM. In MVVM architecture, data and view are not allowed to communicate directly, only through the ViewModel, and the ViewModel is defined as an Observer
    • ViewModelThe ability to observe changes in data and update the corresponding contents of the view
    • ViewModelThe ability to listen for changes in views and notify data of changes

Vue. Js is an MVVM implementor, and its core is to realize DOM listening and data binding.

Vi. Why use vue.js

  • Lightweight, small size is an important indicator. Vue. Js compressed is only 20 KB (Angular compressed 56kb+, React compressed 44kb+)
  • Mobile first. More suitable for mobile, such as mobile Touch events
  • Easy to get started, smooth learning curve, well-documented
  • It leverages the strengths of Angular (modularity) and React (virtual DOM) and has its own unique features, such as computed properties
  • Open source, high community activity

The first Vue program

1 shows

  • IDEA can install Vue plug-ins!

Note: Vue does not support IE8 and below because Vue uses ECMAScript 5 features that IE8 cannot emulate. But it supports all ECMAScript 5 compatible browsers.

2 download

  • Development version

    • Contains full warning and debug modes: vuejs.org/js/vue.js
    • 30.96KB min + gzip: vuejs.org/js/vue.min….
  • CDN

    •   <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
      Copy the code
    •   <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
      Copy the code

Three examples of the demo

  • Vue. Js is an MVVM implementor, and its core is to realize DOM listening and data binding.

1. Create an HTML file

2. Import vue.js

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
Copy the code

3. Create an Yue object instance

<script>
    var vm = new Vue({
        el: "#app"./ / Model: data
        data: {
            message: "Hello, Vue!"}}); </script>Copy the code
  • el:"#app": ID of the binding element
  • data:{message: "Hello,Vue!" }The data object has a property called message and an initial value of “Hello,Vue!”

4. Bind instances to page elements

<div id="app"> {{message}} </div>
Copy the code

The data binding function is implemented by wrapping the Vue created property named Message in the bound element with a double {}. This provides the desired effect for the ViewModel layer.

5. Complete code

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My First Vue</title>
</head>

<body>
    <! -- View layer template -->
    <div id="app"> {{message}} </div>

    <! -- 1. Import vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
    <script>
        //viewModel implements bidirectional binding with Model, dynamically updating view data
        var vm = new Vue({
            el: "#app"./ / Model: data
            data: {
                message: "Hello, Vue!"}});</script>
    
</body>
</html>
Copy the code

ViewModel bidirectional binding

To get a more intuitive experience of Vue’s bidirectional binding, we can demonstrate it directly on the browser console:

At this point, you can modify the value by typing vm.message directly in the console. Data can be omitted. In this operation, the content of the page is changed without actively manipulating the DOM, thanks to Vue’s data binding feature.

In MVVM mode, the ViewModel layer is required to use the observer mode to realize the monitoring and binding of data, so as to achieve the fast response of data and view.

Basic Grammar & Usage

  • Now that the data is associated with the DOM, everything is responsive.

  • We manipulate the properties of objects on the console, and the interface can be updated in real time.

1. V-bind binds data to element attributes

We can use V-bind to bind data and element attributes!

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My First Vue</title>
</head>

<body>
    <! -- View layer template -->
    <div id="app">
        <span v-bind:title="message">Hover for a few seconds to see the prompt for dynamic binding here!</span>
      </div>

    <! -- 1. Import vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
    <script>
        //viewModel implements bidirectional binding with Model, dynamically updating view data
        var vm = new Vue({
            el: "#app"./ / Model: data
            data: {
                message: "Hello, Vue!"}});</script>
    
</body>
</html>
Copy the code

Console:

vm.message="wonderful U"
Copy the code

2. V-if & V-else conditional rendering

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My First Vue</title>9
</head>

<body>
    <! -- View layer template -->
    <div id="app">
        <! -- <h1 v-if="ok">Yes</h1> <h1 v-else=>No</h1> -->
        <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. Import vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
    <script>
        //viewModel implements bidirectional binding with Model, dynamically updating view data
        var vm = new Vue({
            el: "#app"./ / Model: data
            data: {
                // ok: true,
                type: 'A',}});</script>
    
</body>
</html>
Copy the code

Console:

vm.type=1
vm.type='D'
vm.type='E'
vm.type='A'
Copy the code

3. V-for list rendering

<! -- * @Author: your name * @Date: 2020-10-06 16:48:08 * @LastEditTime: 2020-10-06 22:52:08 * @LastEditors: Please set LastEditors * @Description: In User Settings Edit * @FilePath: \Vue\chapter-1\demo1.html -->
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My First Vue</title>
</head>

<body>
    <! -- View layer template -->
    <div id="app">
        <! -- v -- for=" array element in source array "-->
        <li v-for="(item, index) in items">
            <! Access by iterating through variables -->
            {{item.message}} - {{index}}
        </li>
    </div>

    <! -- 1. Import vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
    <script>
        //viewModel implements bidirectional binding with Model, dynamically updating view data
        var vm = new Vue({
            el: "#app"./ / Model: data
            data: {
                items: [{message: 'Melody'},
                    {message: 'Jerry'},]}});</script>
    
</body>
</html>
Copy the code

Items are the source data array, and item is the alias of the array element being iterated over.

4. V-on binding event

  • You can usev-onDirectives listen for DOM events and run some JavaScript code when triggered.
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My First Vue</title>
</head>

<body>
    <! -- View layer template -->
    <div id="app">
        <button v-on:click="sayHi">Am I</button>
        <p>The button above has been clicked {{counter}} times.</p>
    </div>

    <! -- 1. Import vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
    <script>
        //viewModel implements bidirectional binding with Model, dynamically updating view data
        var vm = new Vue({
            el: "#app"./ / Model: data
            data: {
                counter: 0.message: "What do you want with me? You order when I tell you to?",},methods: {  // Methods must be defined in Vue's methods object, v-on binding events
                sayHi: function (event) {
                    // This refers to the current Vue instance object
                    this.counter += 1,
                    alert(this.message)
                }
            },
        });
    </script>
    
</body>
</html>
Copy the code

There are events for the Vue, and some events for the front page itself!

Click is a vUE event that can be bound to a method event in methods in VUE!

Cn.vuejs.org/v2/guide/ev…

5. V-model Vue bidirectional binding

5.1 What is Bidirectional binding

Vue. Js is an MVVM framework, which stands for data bidirectional binding, namely:

  • When the data changes, the view changes,

  • As the view changes, so does the data.

    This is the essence of vue.js.

It is worth noting that when we say two-way data binding, it must be for UI controls. Non-ui controls do not involve two-way data binding.

One-way data binding is a prerequisite for using state management tools.

If we use VUEX, the data flow is also unidirectional, which conflicts with two-way data binding.

5.2 Why Implement bidirectional data binding

In vue. js, if you use vuex, the data is actually one-way, so it is called two-way data binding, which is used for UI controls. For us to deal with forms, vue. js two-way data binding is particularly comfortable to use.

  • That is, they are not mutually exclusive. Single item is used in global data flow to facilitate tracking.
  • Local data flow is bidirectional and easy to operate.

5.3 Use two-way data binding in forms

  • You can usev-modelInstruction in form<input>,<textarea><select>Creates a bidirectional data binding on the element.

It automatically selects the correct method to update the element based on the control type.

For all its magic, v-Models are essentially syntax sugar.

It listens for user input events to update data and performs special processing for extreme scenarios.

Note: The V-Model ignores the initial values of the value, Checked, and Selected features of all elements and always uses the Vue instance data as the data source. You should declare this in JavaScript in the data option of the component.

5.4 text field

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My First Vue</title>
</head>

<body>
    <! -- View layer template -->
    <div id="app">Input text:<textarea v-model="message"></textarea> <hr>Two-way data binding: {{message}}</div>

    <! -- 1. Import vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
    <script>
        //viewModel implements bidirectional binding with Model, dynamically updating view data
        var vm = new Vue({
            el: "#app"./ / Model: data
            data: {
                message: "Initial text",}});</script>
    
</body>
</html>
Copy the code

5.5 radio buttons

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My First Vue</title>
</head>

<body>
    <! -- View layer template -->
    <div id="app">Gender:<input type="radio" name="sex" value="Male" v-model="MelodyJerry"><input type="radio" name="sex" value="Female" v-model="MelodyJerry"><hr>
        <p>MelodyJerry. Sex: {{MelodyJerry}}</p>
            
    </div>

    <! -- 1. Import vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
    <script>
        //viewModel implements bidirectional binding with Model, dynamically updating view data
        var vm = new Vue({
            el: "#app"./ / Model: data
            data: {
                MelodyJerry: ' ',}});</script>
    
</body>
</html>
Copy the code

5.6 a drop-down box

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My First Vue</title>
</head>

<body>
    <! -- View layer template -->
    <div id="app">The drop-down box:<select v-model="selected">
            <option value="" disabled>-- Please select --</option>
            <option>A</option>
            <option>B</option>
            <option>C</option>
            <option>D</option>
        </select>
        <hr>Selected value: {{selected}}</div>

    <! -- 1. Import vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
    <script>
        //viewModel implements bidirectional binding with Model, dynamically updating view data
        var vm = new Vue({
            el: "#app"./ / Model: data
            data: {
                selected: ' ',}});</script>
    
</body>
</html>
Copy the code

Note: If the initial value of the V-model expression does not match any of the options, the element will be rendered “unchecked”. In iOS, this prevents the user from selecting the first option. Because in this case, iOS does not trigger the change event. Therefore, it is recommended to provide a null disable option like the one above: value=”” disabled.

5.7 check box

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My First Vue</title>
</head>

<body>
    <! -- View layer template -->
    <div id="app">Single check box:<input type="checkbox" id="checkbox" v-model="checked">
    <hr>Checked value: {{checked}}</div>

    <! -- 1. Import vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
    <script>
        //viewModel implements bidirectional binding with Model, dynamically updating view data
        var vm = new Vue({
            el: "#app"./ / Model: data
            data: {
                checked : false,}});</script>
    
</body>
</html>
Copy the code

Ix. Vue components

  • Component based
  • Learn more about components

1. What are components

  • Components are reusableVueExamples, in plain English, are a set of reusable templates, along with JSTL’s custom tags and Thymeleaf’sth:fragmentAnd so on the framework has the same wonderful.

Typically an application is organized as a nested component tree:

For example, you might have headers, sidebars, content areas, and so on, each of which contains other components like navigation links, blog posts, and so on.

In order to be used in templates, these components must first be registered for Vue to recognize.

There are two types of component registration:

  • Global registration
  • Local registration

So far, our components are only registered globally through Vue.com Ponent:

Vue.component('my-component-name', {
  // ... options ...
})
Copy the code

Globally registered components can be used in any newly created Vue root instance (via New Vue) after they have been registered, as well as in templates for all children of their component tree.

That’s all you need to know about component registration so far, and if you’ve read this page and are comfortable with it, we recommend you come back and finish registering your component.

2. First VUE component

  • Register components firstDefine a Vue component component
    • Vue.component(): Register component
    • my-component-name: Name of the custom component
    • template: Template for the component
  • Then instantiate Vue

Component names must be all lowercase; any uppercase will register an error

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My First Vue</title>
</head>

<body>
    <! -- View layer template -->
    <div id="app">
        <! -- <li> Hello, MelodyJerry! </li> -->
        <melodyjerry> Hello, MelodyJerry! </melodyjerry>
    </div>

    <! -- 1. Import vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
    <script>
        // First register the component and define a Vue component
        Vue.component("melodyjerry", {// The component name must be all lowercase. If it is uppercase, an error will be registered
            template: '<li> This is a Vue-Component. </li>'
        });

        // instantiate Vue again
        var vm = new Vue({
            el: "#app"});</script>
    
</body>
</html>
Copy the code

3. Prop Transfers parameters

Note: By default, the props property cannot be capitalized.

  • Prop case
  • Prop type
  • Pass static or dynamic Prop
    • Passing in a number
    • Pass in a Boolean value
    • Passing in an array
    • Passing in an object
    • Pass in all properties of an object
  • Unidirectional data flow
  • Prop validation
    • Type checking
  • The Attribute of the Prop
    • Replace or merge existing attributes
    • Disabling Attribute Inheritance

Reference: blog park, official documents

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My First Vue</title>
</head>

<body>
    <! -- View layer template -->
    <div id="app">
        <! -- <li> Hello, MelodyJerry! </li> -->
        <melodyjerry v-for="item in items" v-bind:prop="item"> Hello, MelodyJerry! </melodyjerry>
    </div>

    <! -- 1. Import vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
    <script>
        // First register the component and define a Vue component
        Vue.component("melodyjerry", {// The component name must be all lowercase. If it is uppercase, an error will be registered
            //prop: pass parameters
            props: ['prop'].// By looping through prop, V-bind :prop binds the property 'prop', which is passed to the template as a medium
            // The template for the component
            template: '<li> {{prop}} </li>'
        }); 

        // instantiate Vue again
        var vm = new Vue({
            el: "#app".data: {
                items: ["Java"."Python"."Vue"]}});</script>
    
</body>
</html>
Copy the code

10. Axios asynchronous communication

1. What is Axios

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

  • Created from the browserXMLHttpRequests
  • Create HTTP requests from Node.js
  • Support for the Promise API [JS chained programming]
  • Intercept requests and responses
  • Transform request data and response data
  • Cancel the request
  • Automatically convert JSON data
  • Client support against XSRF (Cross-site Request Forgery)

GitHub:github.com/axios/axios

Chinese document: www.axios-js.com/

2. Why use Axios

Since vue.js is a view-layer framework and the author (Yu Stream) strictly follows SoC (separation of attention principle), vue.js does not contain Ajax communication function. To solve the communication problem, the author developed a plug-in named vue-Resource separately. However, maintenance of the plug-in was stopped after the 2.0 release and the Axios framework was recommended. Use jQuery sparingly, because it manipulates the Dom too often!

3. Import Axios

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Copy the code

4. The demo

Most of the interfaces we developed are in JSON format. We can first simulate a section of JSON data in the project, and the data content is as follows: Create a file named data. JSON and fill in the above content, and put it in the root directory of the project.

{
    "name": "MelodyJerry"."url": "https://melodyhub.ltd/"."page": 1."isNonProfit": true."address": {
      "street": "Guangzhou"."city": "Guangdong"."country": "China"
    },
    "links": [{"name": Blog Park."url": "https://www.cnblogs.com/melodyjerry/"
      },
      {
        "name": "GitHub"."url": "melodyhub.ltd"
      },
      {
        "name": "Gitee"."url": "https://melodyjerry.gitee.io/"}}]Copy the code

Create a new demo.html to try asynchronous communication with Axios:

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My First Vue</title>

    <! --v-clock fix flicker -->
    <style>
        [v-clock] {
            display: none;
        }
    </style>
</head>

<body>
    <! -- View layer template -->
    <div id="vue" v-clock>
       <div>Name: {{info. Name}}</div>
       <div>Address: {{info. Address. Country}} - {{info. Address. City}} - {{info. Address. Street}}</div>
       <div>Blog:<a v-bind:href="info.url" target="_blank">{{info.url}}</a></div>
    </div>

    <! -- 1. Import vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
    <! - import axios -- -- >
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.19.2/axios.min.js"></script>

    <script>
        var vm = new Vue({
            el: "#vue".data: {
                items: ['Java'.'Python'.'Php']},//data: attributes of the VM
            //data() : vm method
            data(){
                return{
                    // The return parameter of the request must be the same as the JSON string
                   info: {name: null.url: null.address: {
                           street: null.city: null.country: null}}}},// Hook functions, chain programming, new ES6 features
            mounted(){
                axios.get(".. /data.json").then(response= > (this.info = response.data))
                axios.get(".. /data.json").then(response= > (console.log(response.data)))
            }
        })
    </script>
    
</body>
</html>
Copy the code
  • Data: indicates the VM attributes

  • Data () : VM method

    • return{}: The return parameter of the request must be the same as the JSON string
  • Mounted (){} : specifies the hook function

Description:

  1. It’s used herev-binda:hrefThe attribute valueBind to data in the Vue instance
  2. Request using the Axios framework’s GET methodAJAXAutomatically encapsulates data into Vue instance data objects
  3. Our data structure in data has to be equal toAjaxResponsebackData format matching!
  4. About the codeV-clock solves the flicker problem, refer toVue instruction: Solve the page flicker problem by V-clock

11. Calculate attributes

Documents: cn.vuejs.org/v2/guide/co…

1. What are calculated attributes

  • The key to calculating attributes is thatattributeIn two words, first of all it’s aattributeAnd then this property hasTo calculateThe ability (to calculate is the verb) hereTo calculateIt’s a function;
  • Simply put, it is an attribute that caches the results of the calculation (turning the behavior into a static attribute), and nothing more; Think of it as caching!

2. Examples of the demo

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My First Vue</title>
</head>

<body>
    <! -- View layer template -->
    <div id="app">
        <! -- Call methods with () -->
        <p>currentTime1: {{currentTime1()}}</p>
        <! -- Calling a method that computes attributes computed, cannot use () -->
        <p>currentTime2: {{currentTime2}}</p>
    </div>

    <! -- 1. Import vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
    
    <script>
        var vm = new Vue({
            el: "#app".data: {
                message: "hello,melodyjerry."
            },
            methods: {
                currentTime1: function() {
                    var Xmas95 = new Date("December 25, 1995 23:15:30");
                    return Xmas95.getDay(); / / 1. Returns the day of the week: 0 for Sunday,1 for Monday, and 2 for Tuesday}},// Calculate attributes
            computed: { // Methods in methods and computed cannot have the same name; After the same name, only methods in methods are called
                currentTime2: function() {
                //currentTime1: function() {
                    return Date.now(); // Return a timestamp}},})</script>
    
</body>
</html>
Copy the code

Note: the following is the record of stomping pits found in my study, not necessarily correct!!

  • callmethodsThe method in,Have to ()
    • methodsismethods
  • callcomputedThe method ofCan't use ()
    • computedisCalculate attribute, it isattribute
  • methods,computedMethod name inCan't wish; After the nuptial,Only methods are calledThe methods in

3. Advanced

CurrentTime2 add this.message; Try:

// Calculate attributes
computed: { // Methods in methods and computed cannot have the same name; After the same name, only methods in methods are called
    currentTime2: function() {
    //currentTime1: function() {
        this.message;
        return Date.now(); // Return a timestamp}},Copy the code

Try them separately in the console:

4. Conclusion

When you call a method, you need to perform a calculation every time, and since there must be calculation overhead, what if the result doesn’t change very often?

  • That’s when you think about itCache the resultThis can be easily done using computed properties,Computed attributiveThe main feature is to cache results that do not change very oftenTo save our system overhead.

12. Slot: Content distribution

Documents: cn.vuejs.org/v2/guide/co…

1. What is a slot

Vue implements a content distribution API inspired by the draft Web Components specification that uses

elements as an outlet for hosting distribution content.

It allows you to compose components like this:

<navigation-link url="/profile">
  Your Profile
</navigation-link>
Copy the code

Then you might write in the
template:

<a
  v-bind:href="url"
  class="nav-link"
>
  <slot></slot>
</a>
Copy the code

When the component is rendered,
will be replaced with “Your Profile”. The slot can contain any template code, including HTML:

<navigation-link url="/profile">
  <! Add a Font Awesome icon -->
  <span class="fa fa-user"></span>
  Your Profile
</navigation-link>
Copy the code

Even other components:

<navigation-link url="/profile">
  <! Add an icon component -->
  <font-awesome-icon name="user"></font-awesome-icon>
  Your Profile
</navigation-link>
Copy the code

If the template of
does not contain a

element, anything between the component’s start tag and end tag is discarded.

2. Content distribution

In vue.js we use the

element as an outlet for hosting distribution content, which the authors call slots, which can be used in composite component scenarios.

3. The demo

  • demand

For example, if you want to make a todo component, which consists of todo-title and todo-items, but these three components are independent of each other, how do you do that?

  • Step 1: Define a backlog component
<! -- Component: todo -->
<div id="app"">
    <todo></todo>
</div>
              
<! -- 1. Import vue.js -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
    
<script>
    Vue.component('todo', {
        template: '<div>\
                    <div>todo</div>\
                    <ul>\
                        <li>Linux</li>\
                        <li>Spring Boot</li>\
                        <li>Vue</li>\
                    </ul>\
                   </div>'});</script>
Copy the code
  • Step 2: We need to dynamically bind the title and value of the to-do item. How do we do that? We can leave a slot!
  1. Leave a slot for the above code, i.e<slot>:
Vue.component('todo', {
    template: '<div>\
                    <slot name="todo-title"></slot>\
                    <ul>\
                        <slot name="todo-items"></slot>\
                    </ul>\
               </div>'});Copy the code
  1. Define a file namedtodo-titleThe todo title component andtodo-itemsTo do content components:
Vue.component('todo-title', {
    props: ['title'].template: '<div>{{title}}</div>'
});
Vue.component('todo-items', {
    // The index of the array is the index of the array.
    props: ['index'.'item'].template: '<li>{{index + 1}}. {{item}}</li>'});Copy the code
  1. Instantiate Vue and initialize data:
var vm = new Vue({
    el: '#app'.data: {
        todoTitle: 'Jerry learn JavaWeb'.todoItems: ['Linux'.'Spring Boot'.'Vue']}});Copy the code
  1. Insert these values through the slot:
<! -- Component: todo -->
<div id="app"">
    <todo>
        <todo-title slot="todo-title" 
            v-bind:title="todoTitle">
        </todo-title>
        <todo-items slot="todo-items" 
            v-for="(item, index) in todoItems" 
            v-bind:item="item" 
            v-bind:index="index":key="index"></todo-items>
        </todo-items>
    </todo>
</div>
Copy the code

Description:

Our todo-title and Todo-Items components were distributed to the Todo-title and Todo-Items slots of the ToDO component, respectively.

Custom events

Documents: cn.vuejs.org/v2/guide/co…

1. What are custom events

As you can see from the “slot: content distribution” code above, the data item is in the Vue instance, but the deletion operation is done in the component. How can the component delete the data in the Vue instance?

At this point, parameter passing and event distribution are involved. Vue provides us with the function of customizing events to help us solve this problem:

  • useThis.$emit (' custom event name ', parameter)
this.$emit('myEvent')
Copy the code

Listening on the kebab-case version of this name has no effect:

<! -- No effect --><my-component v-on:my-event="doSomething"></my-component>
Copy the code

Unlike components and prop, the event name is not used as a JavaScript variable name or property name, so there is no reason to use camelCase or PascalCase. And the V-ON event listener is automatically converted to all lowercase in the DOM template (because HTML is case insensitive), so V-on :myEvent will become V-on :myEvent — making myEvent impossible to listen on.

Therefore, we recommend that you always use the event name of kebab-case.

2. Customize the V-Model of components

2.2.0 + added

By default, a V-Model on a component makes use of a prop named Value and an event named input, but input controls of types like checkboxes, checkboxes, and so on May use value attributes for different purposes. The Model option can be used to avoid such conflicts:

Vue.component('base-checkbox', {
  model: {
    prop: 'checked'.event: 'change'
  },
  props: {
    checked: Boolean
  },
  template: `  `
})
Copy the code

Now when using the V-Model on this component:

<base-checkbox v-model="lovingVue"></base-checkbox>
Copy the code

The value of lovingVue here will be passed to the prop named Checked. The lovingVue property will also be updated when

fires a change event with a new value.

Note that you still need to declare checked prop in the props option of the component.

3. The demo

  1. In the case of vue, addedmethodsObject and defines a name namedremoveTodoItemsMethod:
var vm = new Vue({
    el: '#app'.data: {
        todoTitle: 'Jerry learn JavaWeb'.todoItems: ['Linux'.'Spring Boot'.'Vue'],},methods: {
        // This method can be triggered by custom events in the template
        removeTodoItems: function(index) {
            console.log("Delete" + this.todoItems[index] + "Success");
            // splice(): the splice() method adds/removes items from/array and returns the deleted items, where index is the location of the added/deleted items and 1 is the number of deleted items
            this.todoItems.splice(index, 1); }}});Copy the code
  1. Modify thetodo-itemsThe code for the todo content component, adding a delete button and binding the event:
Vue.component('todo-items', {
    // The index of the array is the index of the array.
    props: ['index'.'item'].// ":" is short for the instruction "v-bind", "@" is short for the instruction "V-on"; "." Is the modifier
    // Only methods of the current component can be bound
    template: '< li > < button @ click = "remove_component" > delete < / button > {{index + 1}}, {{item}} < / li >'.methods: {
        remove_component: function(index) {
            // Remove is the name of the custom event, which needs to be assigned in HTML using v-on:remove
            this.$emit('remove', index); }}});Copy the code
  1. Modify thetodo-itemsHTML code for the to-do content component, adding a custom event such as callremove, can be bound to component methods and then bound to vue methods:
<! -- Added v-on:remove="removeTodoItems(index)" custom event that calls method removeTodoItems defined in Vue instance -->
<todo-items slot="todo-items" 
    v-for="(item, index) in todoItems" 
    v-bind:item="item" 
    v-bind:index="index"
    v-on:remove="removeTodoItems(index)"></todo-items>
</todo-items>
Copy the code
  • Complete code:
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My First Vue</title>
</head>

<body>
    <! -- Component: todo -->
    <div id="app"">
        <todo>
            <todo-title slot="todo-title" 
                v-bind:title="todoTitle">
            </todo-title>

            <! -- Added v-on:remove="removeTodoItems(index)" custom event that calls method removeTodoItems defined in Vue instance -->
            <todo-items slot="todo-items" 
                v-for="(item, index) in todoItems" 
                v-bind:item="item" 
                v-bind:index="index"
                v-on:remove="removeTodoItems(index)"></todo-items>
            </todo-items>
        </todo>
    </div>

    <! -- 1. Import vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.min.js"></script>
    
    <script>
        Vue.component('todo', {
            template: '
       
\ \
    \ \
\
'
}); Vue.component('todo-title', { props: ['title'].// Don't use camel name for the props pass parameter, otherwise the data won't render to the page template: '<div>{{title}}</div>' }); Vue.component('todo-items', { // The index of the array is the index of the array. props: ['index'.'item'].// ":" is short for the instruction "v-bind", "@" is short for the instruction "V-on"; "." Is the modifier // Only methods of the current component can be bound template: '< li > < button @ click = "remove_component" > delete < / button > {{index + 1}}, {{item}} < / li >'.methods: { remove_component: function(index) { // Remove is the name of the custom event, which needs to be assigned in HTML using v-on:remove this.$emit('remove', index); }}});// instantiate var vm = new Vue({ el: '#app'.data: { todoTitle: 'Jerry learn JavaWeb'.todoItems: ['Linux'.'Spring Boot'.'Vue'],},methods: { // This method can be triggered by custom events in the template removeTodoItems: function(index) { console.log("Delete" + this.todoItems[index] + "Success"); // splice(): the splice() method adds/removes items from/array and returns the deleted items, where index is the location of the added/deleted items and 1 is the number of deleted items this.todoItems.splice(index, 1); }}});
</script> </body> </html> Copy the code

Fourteen, introduction summary

  • Vue follows the Soc focus separation principle

  • Is a pure view layer framework

  • There are no AJAX communication features

    • In order to solve the communication problem, needUse the Axios framework for asynchronous communication
  • Vue’s core library focuses only on the view layer, making it easy to integrate with third-party libraries or existing projects

  • HTML + CSS + JS: View: refresh the data provided by the background

The core

  • Data driven
  • componentization
  • Virtual DOM

advantages

  • Learn from theAngulaJSthemodularThe development of
  • Learn from theReacttheVirtual DOM
    • Virtual DOM: puts DOM operations into memory for execution

Common attributes

  • v-if
    • v-else-if
    • v-else
  • v-for
  • v-on: Binding event, for short@
  • v-model: Data bidirectional binding
  • v-bind: Binds parameters to a component:

componentization

  • Combination of componentsslot: slot
  • Internal component binding events need to be usedThis.$emit(" event name ", parameter);
  • Calculate attributeFeatures:Cache calculated data

Apply colours to a drawing mechanism

Photo source: blog.csdn.net/github_3751…

SoC concerns separation principle

Content from: www.cnblogs.com/wenhongyu/a…

concept

  • Separation of concerns (SOC) is the ability to “identify, encapsulate, and manipulate” software components that are only associated with a “specific concept, goal” (concern), i.e. the ability to identify, encapsulate, and manipulate concerns.

  • Is a principle for dealing with complexity. Because intermingling of concerns can greatly increase complexity, the ability to separate and treat different concerns separately is a principle and a method of dealing with complexity.

  • Separation of concerns is a core concept of aspect-oriented programming. Separation of concerns makes the code to solve domain-specific problems separate from the business logic.

  • The code of business logic no longer contains the invocation of domain-specific code (the domain-specific code is abstracted into fewer code, such as encapsulating the code into function or class). The relationship between business logic and domain-specific problem is encapsulated and maintained by side. Changes that would otherwise be scattered throughout the application can be well managed.

Be specific (concepts are difficult to understand)

  1. Good architectural design must neatly encapsulate the points of change into different parts of the software system. To do this, there must be a separation of concerns.

  2. A good architecture must keep each concern separate, meaning that changes in one part of the system do not affect other parts.

  3. Clearly identify which parts need to be changed, even if they do.

  4. If the architecture needs to be extended, the impact will be minimized and everything that is already working will continue to work.

Four sentences summarize the above statement

  • “Changes in one part of the system don’t affect other parts.”
  • “Even if you need to change, you can clearly identify the parts that need to change.”
  • “If the architecture needs to be extended, the impact will be minimized and everything that already works will continue to work.”

conclusion

  • The principle of separation of concerns is not only embodied in design methods such as problem solving, algorithm design and software design, but also in software development process, software project management and software development methodology.
  • In a sense, it is the separation of perspectives and differences in focus of different software development concerns that lead to the evolution and development of software development techniques and methods.

Other instructions

The actual development of Vue is:

  • Based on theNodeJS
  • The actual usevue-cliThe scaffold
  • Network communication:axios
  • Page hopping and routingvue-router
  • State managementvuex
  • UI
    • Element UI(Ele. me)
    • ICE(Alibaba)

Vue life cycle

The official documentation

References: ①, ②, ③ with notes

A Vue instance has a complete life cycle, that is, from the beginning to create, initialize data, compile templates, mount DOM, render, update, render, uninstall, etc., we call this a Vue life cycle. Vue instance is the process from creation to destruction.

Throughout the life cycle of the Vue, it provides a series of events that allow us to register JS methods when the event is triggered. It allows us to control the overall situation with our own registered JS methods, and this in these event response methods refers directly to the instance of the Vue.