Teach you a quick start Vue

Vue

After watching the crazy video of station B, Xiaobian benefited a lot and wrote down this article on the way to study
Small partners can also get the complete video of crazy God from station B!
Home page of crazy God B station

Online CDN

<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>

Modular development + virtual DOM

1 front end core analysis

1.1 VUE overview

Vue (pronounced / vju /, similar to view) is a progressive framework for building user interfaces, which was released in February 2014. Unlike other large frameworks, Vue is designed to be applied layer by layer from bottom to top. Vue's core library only focuses on view layers, which is not only easy to start, but also easy to integrate with third-party libraries (such as Vue Router: jump, Vue resource: communication, vuex: Management) or existing projects

Vue's core library only focuses on view layers to facilitate integration with third-party libraries or existing projects.

HTML + CSS + JS: View: show the user and refresh the data given by the background

Network communication: axios

Page Jump: Vue router

Status management: vuex

Vue-UI : ICE , Element UI

1.2 front end three elements

  • HTML (structure): Hyper Text Markup Language, which determines the structure and content of web pages
  • CSS (presentation): cascading style sheets to set the presentation style of web pages
  • JavaScript (behavior): it is a weak type 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.2.1 structural layer

HTML

Is the skeleton of the web page

1.2.2 presentation layer

CSS

CSS cascading style sheet is a markup language, not a programming language, so it can't customize variables, reference, etc. in other words, it doesn't have any syntax support. Its main defects are as follows:

  • The syntax is not strong enough, for example, it cannot be nested, which leads to the need to write a lot of repeated selectors in modular development;
  • There is no variable and reasonable style reuse mechanism, so that the logically related attribute values must be repeatedly output in the form of literal quantity, which makes it difficult to maintain;
    This has led to an unprovoked increase in our workload. In order to solve this problem, front-end developers will use a tool called CSS preprocessor to provide CSS missing style layer reuse mechanism, reduce redundant code and improve the maintainability of style code. It greatly improves the development efficiency of the front end in style.

So CSS preprocessor appeared

What are the commonly used CSS preprocessors

  • SASS: Based on Ruby, it is powerful through server-side processing. High parsing efficiency. You need to learn Ruby language, which is more difficult than LESS.
  • LESS: Based on NodeJS and processed by the client, it is easy to use. The function is simpler than SASS, and the parsing efficiency is lower than SASS, but it is enough in actual development. Therefore, if our background personnel need it, we recommend using LESS.

1.2.3 behavior layer

JavaScript

JavaScript is a weak type scripting language. Its source code does not need to be compiled before it is sent to the client. Instead, it sends the character code in text format to the browser for interpretation and operation.

Native JS development

Native JS development, that is, let's follow the development method of [ECMAScript] standard, referred to as es, which is supported by all browsers. Up to now, ES standard has been published in the following versions:

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

The difference is to gradually add new features.
TypeScript Microsoft standard
TypeScript is a free and open source programming language developed by Microsoft. It is a superset of JavaScript and essentially adds optional static types and class based object-oriented programming to the language. Led by Anders hellsberg (father of C#, Delphi, TypeScript; founder of. NET). The feature of the language is that in addition to the ES features, it also includes 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) to be correctly executed by browsers.

JavaScript framework

  • JQuery: the well-known JavaScript library has the advantage of simplifying DOM operation, but the disadvantage is that DOM operation is too frequent, affecting the 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 background MVC mode to the front-end and adding the concept of modular development. In cooperation with Microsoft, it adopts TypeScript syntax for development; Friendly to background programmers, not very friendly to front-end programmers; The biggest disadvantage is that the version iteration is unreasonable (for example, generation 1 – > generation 2, except for the name, there are basically two things; Angular6 has been launched as of the time of publishing the blog)
  • React: produced by Facebook, a high-performance JS front-end framework; The feature is that a new concept [virtual DOM] is proposed to reduce real DOM operations, simulate DOM operations in memory, and effectively improve the front-end rendering efficiency; The disadvantage is that it is complex to use, because you need to learn an additional [JSX] language;
  • Vue: a progressive JavaScript framework. The so-called progressive means to gradually realize new features, such as modular development, routing, state management and other new features. It combines the advantages of Angular (Modular) and react (virtual DOM);
  • Axios: front end communication framework; Because the boundary of Vue is very clear, it is to deal with DOM, so it does not have communication capability. At this time, it is necessary 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;

1.3 front end technology

1.3.1 UI framework

  • Ant Design: produced by Alibaba and based on React UI framework
  • ElementUI, iview, ice: produced by hungry, Vue based UI framework
  • BootStrap: an open source toolkit for front-end development launched by Teitter
  • AmazeUI: also known as "sister UI", an HTML5 cross screen front-end framework

1.3.2 JavaScript build tool

  • Babel: JS compilation tool, mainly used for ES new features not supported by the browser, such as TypeScript compilation
  • WebPack: module packer, which is mainly used to pack, compress, merge and load in order

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

1.3.3 three ends in one

Hybrid App

The main purpose is to achieve a set of code three terminal unification (PC, Android:. apk, iOS:. ipa) and call to the underlying hardware of the device (such as sensor, GPS, camera, etc.). The packaging methods are mainly the following two:

  • Cloud packaging: hbuild - > hbuildx, produced by dccloud; API Cloud
  • Local packaging: Cordova (formerly PhoneGap)

Wechat applet

See wechat's official website for details. Here is a framework to facilitate wechat applet UI development: WeUI

1.3.4 back end technology

In order to facilitate development, front-end personnel also need to master certain back-end technologies, but we Java background personnel know that the background knowledge system is extremely huge and complex. Therefore, in order to facilitate front-end personnel to develop background applications, technologies such as Node JS appear. The author of Node JS has claimed to give up Node JS (it may annoy the author because of the poor architecture and the cumbersome node modules) and start developing De no with a new architecture
Since it is a background technology, it must also need a framework and project management tools. The Node JS framework and project management tools are as follows:

  • Express: Node JS framework
  • Koa: Express simplified
  • NPM: integrated project management tool, similar to Maven
  • YARN: an alternative to NPM, similar to the relationship between Maven and Gradle

2 MVVM

2.1 what is MVVM

MVVM originates from the classic MVC (modi view controller) mode. The core of MVVM is the ViewModel layer, which is responsible for transforming the data objects in the Model to make the data easier to manage and use. Its functions are as follows:

  • This layer performs bidirectional data binding with the view layer upward
  • Data interaction with the Model layer through interface requests

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-zfmjdvqp-163133408776) (E: \ learning file \ JAVA learning \ learning record \ front end \ imgs\image-20210819212331520.png)]

2.2 why use MVVM

MVVM mode is the same as MVC mode. Its main purpose is to separate view and model. It has several advantages:

  • Low coupling: the view can be changed and modified independently of the Model, and a ViewModel can be bound to different views
    In View, when the View changes, the Model can remain unchanged, and when the Model changes, the View can remain unchanged.
  • Reusability: you can put some View logic in a ViewModel to make many views reuse this View logic.
  • Independent development: developers can focus on the development of business logic and data (ViewModel), and designers can focus on page design.
  • Testability: the interface is always difficult to test, but now the test can be written for ViewModel.

2.3 Vue is the implementer of MVVM mode

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-zvyxozy-1631334308778) (E: \ learning file \ JAVA learning \ learning record \ front end \ imgs\image-20210819212639580.png)]

  • Model: the model layer, where JavaScript objects are represented

  • View: view layer, which represents DOM (element of HTML operation)

  • ViewModel: middleware connecting views and data. Vue.js is the implementer of the ViewModel layer in MVVM. In MVVM architecture, data and views are not allowed to communicate directly, but only through ViewModel, which defines an Observer observer

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

  • ViewModel can listen to changes in the view and notify data changes

Vue.js is an implementer of MVVM. Its core is to realize DOM listening and data binding

<!DOCTYPE html>
<html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Title</title>
    </head>
    <body>
    <!--view Layer template-->
    <div id="app">
        <h1 id="mvvm">{{message}}</h1>
    </div>
    </body>

    <!--Import js-->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
    <script>
        var vm = new Vue({
            el: "#app",
            data: {
                //model
                message: "Hello,Vue!"
            }
        })
    </script>
</html>

3 Vue basic syntax

3.1 conditions

Note the definition of arrays and objects

<!DOCTYPE html>
<html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Basic grammar</title>
    </head>
    <body>
    <div id="app">
        <h1 title="I can, too">What about this?</h1>
        
        <h1 v-bind:title="bind">Hover view</h1>

        <b v-if="ifBody=='A'">Background data is A</b>
        <b v-else>Background data is not A</b>

        <p v-for="item in items">
            {{item.message}}
        </p>
    </div>
    </body>

    <!--Import js-->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
    <script>
        var vm = new Vue({
            el: "#app",
            data: {
                bind: "This is a hidden binding title label",
                ifBody: "A",
                items: [
                    {message: "Java"},
                    {message: "MySql"},
                    {message: "Python"},
                    {message: "C"},
                    {message: "C++"},
                    {message: "Matlab"}
                ]
            }
        })
    </script>
</html>

3.2 events

be careful:

  • methods is not a method
  • Attention scope
<!DOCTYPE html>
<html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Binding event</title>
    </head>
    <body>
    <div id="app">
        <button v-on:click="Hi()">Click me</button>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
    <script>
        var vm = new Vue({
            el: "#app",
            data:{message:"Hello,Java Designer!"},
            methods: {
                Hi:function () {
                    alert(this.message)
                }
            }
        });
    </script>
    </body>
</html>

4 bidirectional binding

4.1 what is bidirectional binding

Vue.js is an MVVM framework, that is, two-way data binding, that is, when the data changes, the view will change, and when the view changes, the data will change synchronously. This is the essence of vue.js.

It is worth noting that the two-way data binding must be for UI controls, and non UI controls will 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 single, which will conflict with two-way data binding.

4.2 why should bi-directional data binding be implemented

In Vue.js, if vuex is used, the data is actually one-way. The reason why it is two-way data binding is the UI control used. For us to process forms, Vue.js's two-way data binding is particularly comfortable.

  • Single item is used in global data flow to facilitate tracking

  • Local data flow is bidirectional and easy to operate

4.3 using two-way data binding in forms

You can use the v-model command to create two-way data bindings on forms, and elements. It automatically selects the correct method to update the element according to the control type. Although some magic, v-model is essentially just a syntax sugar. It is responsible for listening to user input events to update data, and some special processing for some extreme scenarios.

Note: v-model will ignore the checked and selected initial values of all elements and always take the Vue instance data as the data source. You should declare it in the data option of the component through JavaScript.

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


    <div id="app">
        <input type="text" v-model="input">{{input}}<br>
<!--        And text fields-->
        Gender:<input type="radio" name="sex" value="male" v-model="sex">male
        <input type="radio" name="sex" value="female">female
        {{sex}}<br>

        Areas:<select name="area" v-model="select">
        <option value="Java">Java</option>
        <option value="Python">Python</option>
        <option value="Go">Go</option>
        </select>
        {{select}}<br>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
    <script>
        var vm = new Vue({
            el: "#app",
            data:{
                input: "",
                sex: "",
                select: ""
            }
        });
    </script>
    </body>
</html>

5 components

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

    <div id="app">
<!--        To use this component, we must pass parameters for it(use v-bind:Parameter name="Bound key")-->
        <get-items v-for="item in items" v-bind:each="item" :head="ui"></get-items>
    </div>


    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
    <script>
        Vue.component("getItems",{
            //A component is defined, its structure is template, and its parameters include each and head
            props:{
                each: Number,
                head:String
            },
//Note that the whole template is a label, and two cannot be defined, which is why a div should be nested outside
            template:`<div>
                <span>{{head}}</span>
                <li>{{each}}</li>
            </div>`
        })
        var vm = new Vue({
            el: "#app",
            data:{
                items: ["Java","Go","Python"],
                ui:"field"
            }
        });
    </script>
    </body>
</html>

There are three ways to pass parameters using templates

  • Use v-bind: parameter name = "bound key"
  • : parameter name = "bound key"
  • Parameter name: Custom parameter

6 Axios

Ajax in virtual DOM

6.1 what is Axios

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

  • Create XMLHttpRequests from the browser

  • Create http request from node.js

  • Support promise API [chain programming in JS]

  • Intercept requests and responses

  • Convert request data and response data

  • Cancel request

  • Automatically convert JSON data

  • The client supports defense against XSRF (Cross Site Request Forgery)

GitHub: https://github.com/axios/axios

Chinese documents: http://www.axios-js.com/

6.2 why use Axios

Because Vue.js is a view layer framework and the author (you Yuxi) strictly abides by the SoC (separation of concerns principle), Vue.js does not include Ajax communication function. In order to solve the communication problem, the author separately developed a plug-in named Vue resource. However, after entering version 2.0, he stopped the maintenance of the plug-in and recommended the Axios framework. Use jQuery less because it operates Dom too often!

6.3 use

Jason data

{
  "name": "Madness theory java",
  "url": "http://baidu.com",
  "page": 1,
  "isNonProfit": true,
  "address": {
    "street": "Light gate",
    "city": "Xi'an, Shaanxi",
    "country": "China"
  },
  "links": [
    {
      "name": "B station",
      "url": "https://www.bilibili.com/"
    },
    {
      "name": 4399,
      "url": "https://www.4399.com/"
    },
    {
      "name": "Baidu",
      "url": "https://www.baidu.com/"
    }
  ]
}

Import online CDNs from Vue and Axios

<!--1.Import vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
<!--Import axios-->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<!DOCTYPE html>
<html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Axios</title>
    </head>
    <body>
    <div id="vue">
        <div>{{info.name}}</div>
        <a v-bind:href="info.url">Point me in</a>
    </div>

    <!--1.Import vue.js-->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
    <!--Import axios-->
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script>
        var vm = new Vue({
            el: "#vue",
            data: {
                items: ['Java','Python','Php']
            },
            //Data: properties of VM
            //data():vm method
            data(){
                return{
                    //The return parameter of the request must be the same as the json string
                    info:{
                        name: null,
                        age: null,
                        sex: null,
                        url: null,
                        address: {
                            street: null,
                            city: null,
                            country: null
                        }
                    }
                }
            },
            //Hook function, chain programming, new features of ES6
            mounted(){
                axios.get("6.axios.json").then(res => (this.info=res.data))
            }
        })
    </script>
    </body>
</html>

7 calculation properties

The key point of calculating attribute is attribute (attribute is a noun). Firstly, it is an attribute. Secondly, this attribute has the ability of calculation (calculation is a verb). The calculation here is a function

Simply put, it is an attribute that can cache the calculation results (convert the behavior into a static attribute), that's all; Think of it as a cache!

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

    <div id="app">
        <h1>{{method1()}}</h1>
        <h1>{{method2}}</h1>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
    <script>
        var vm = new Vue({
            el:"#app",
            data:{},
            methods:{
                method1:function () {
                    return Date.now();
                }
            },
            computed:{
                method2:function () {
                    return Date.now();
                }
            }
        })
    </script>
    </body>
</html>

Conclusion:
  when calling a method, it needs to be calculated every time. Since there is a calculation process, there must be system overhead. What if the result does not change frequently? At this time, we can consider caching the results, which can be easily achieved by using the calculation attribute. The main feature of the calculation attribute is to cache the calculation results that do not change frequently, so as to save our system overhead;

8 slots

slot is to pass parameters to our custom components and reserve space

Official document: if the < todo button > template does not contain a < slot > element, any content between the start tag and the end tag of the component will be discarded

<!DOCTYPE html>
<html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>slot </title>
    </head>
    <body>
    <div id="app">
        <todo>
            <todo-title slot="todo-title" :title="title"></todo-title>
            <todo-body slot="todo-body" v-for="item in items" :item="item"></todo-body>
        </todo>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
    <script>
        Vue.component("todo",{
            props:{

            },
            template:`
            <div>
                <slot name="todo-title"></slot>
                <ul>
                    <slot name="todo-body"></slot>
                </ul>
            </div>
            `
        })
        Vue.component("todo-title",{
            props: {
                title: String
            },
            template:`
            <h1>{{title}}</h1>
            `
        })
        Vue.component("todo-body",{
            props: {
                item: String
            },
            template: `<li>{{item}}</li>`
        })

        var vm = new Vue({
            el:"#app",
            data:{
                title: "field",
                items: ["Java","Python","Go"]
            }
        })
    </script>
    </body>
</html>

9 custom events

<!--        Bind events based on slots-->
<!DOCTYPE html>
<html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>Custom event</title>
    </head>
    <body>
    <!DOCTYPE html>
    <html lang="en">
        <head>
        <meta charset="UTF-8">
        <title>slot </title>
        </head>
        <body>
<!--        Bind events based on slots-->
        <div id="app">
            <todo>
                <todo-title slot="todo-title" :title="title"></todo-title>
<!--                v-on:remove = "Method name (parameter) binding method"-->
                <todo-body slot="todo-body" v-for="(item,index) in items" :item="item" v-on:remove = "remove(index)"></todo-body>
            </todo>
        </div>

        <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.min.js"></script>
        <script>
            Vue.component("todo",{
                props:{

                },
                template:`
            <div>
                <slot name="todo-title"></slot>
                <ul>
                    <slot name="todo-body"></slot>
                </ul>
            </div>
            `
            })
            Vue.component("todo-title",{
                props: {
                    title: String
                },
                template:`
            <h1>{{title}}</h1>
            `
            })
            Vue.component("todo-body",{
                props: {
                    item: String
                },
                //Named transfer method
                emit:"remove",
                //$emit('pass method name ') to use the pass method
                template: `<li>{{item}}<button v-on:click="$emit('remove')">delete<button></li>`
            })

            var vm = new Vue({
                el:"#app",
                data:{
                    title: "field",
                    items: ["Java","Python","Go"]
                },
                methods: {
                    remove: function (index) {
                        this.items.splice(index,1)
                    }
                }
            })
        </script>
        </body>
    </html>
    </body>
</html>

10 Vue-lic

10.1 what is Vue cli

A scaffold officially provided by vue cli is used to quickly generate a vue project template;

The pre-defined directory structure and basic code are just like when we create Maven project, we can choose to create a skeleton project, which is the scaffold, and our development is faster;

Main functions:

  • Unified directory structure
  • Local debugging
  • Hot deployment
  • unit testing
  • Integrated packaging Online

10.2 required environment

  • Node.js : http://nodejs.cn/download/

    The next step is just to install it in your own environment directory

  • Git : https://git-scm.com/downloads
    Mirror image: https://npm.taobao.org/mirrors/git-for-windows/

Confirm that nodejs is installed successfully:

  • cmd, enter node -v to check whether the publication number can be printed correctly!

  • Enter npm-v under cmd to check whether the publication number can be printed correctly!

This npm is a software package management tool, which is similar to apt software installation under linux!

npm is a package management tool in the JavaScript world and the default package management tool for the Node.js platform. npm allows you to install, share, distribute code, and manage project dependencies.

Install Node.js Taobao image accelerator (cnpm)

In this way, the download will be much faster~

# -g is the global installation
npm install cnpm -g

# If the installation fails, replace the source npm source with a Taobao image
# Because npm installation plug-ins are downloaded from foreign servers, they are greatly affected by the network
npm config set registry https://registry.npm.taobao.org

# Then execute
npm install cnpm -g

Installation location: C:\Users\Administrator\AppData\Roaming\npm

10.3 installation Vue cli

#Enter at the command desk

cnpm install vue-cli -g

#Check whether the installation is successful

vue list

10.4 first Vue cli application

To create a Vue project, we randomly create an empty folder on the computer.

Here, I create a new directory D: \ project \ Vue study under disk D;

Create a vue application based on the webpack template

# myvue here is the name of the project. You can name it according to your own needs and directly enter the code under the target folder to create it
vue init webpack myvue

Select no all the way;

Initialize and run

npm install	//Download dependency
npm run dev	//function
Ctrl+C		//sign out

11 WebPack

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

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

Successful test installation: enter the following command, and the installation will be successful if the version number is output

webpack -v
webpack-cli -v

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-9hZpFFyu-1631334308780)(E: \ learning file \ JAVA learning \ learning record \ front end \ imgs\image-20210822165937770.png)]

Expose an interface

exports.sayHi=function (msg) {
    alert(msg)
};
exports.message = "Hello,Vue Designer!"

Introduce this interface

Note that the required () is used here

var hello = require("./hello");
hello.sayHi(hello.message);

Package file configuration

module.exports = {
    entry: './modules/main.js',
    output: {
        filename: './js/bundle.js'
    }
}

Enter webpack in dos window for packaging

Then import the packaged file

<!DOCTYPE html>
<html lang="en">
    <head>
    <meta charset="UTF-8">
    <title>welcome</title>
    </head>
    <body>
    <script src="./dist/js/bundle.js"></script>
    </body>
</html>

12 Vue router routing

Note that the bound component is a component, not a component

Vue Router is the official route manager (path jump) of Vue.js. It is deeply integrated with the core of Vue.js, making it easy to build a single page application. The functions include:

  • Nested routing / view tables

  • Modular, component-based routing configuration

  • Routing parameters, queries, wildcards

  • View transition effect based on Vue.js transition system

  • Fine grained navigation control

  • Links with automatically activated CSS class es

  • HTML5 history mode or hash mode, automatically degraded in IE9

1 installation

Test learning based on the first Vue cli

Check the node first_ Is there a Vue router in modules

Vue router is a plug-in package, so we still need to install it with npm/cnpm. Open the command line tool, enter your project directory, and enter the following command.

npm install vue-router --save-dev

Go to node after installation_ Modules path to see if there is Vue router information. If yes, it indicates that the installation is successful.

2 use

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/router";

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  //Use router (a Vue router is created internally)
  router,
  //Our index.html is bound here
  el: '#app',
  //Importing Vue components
  components: { App },
  //structure
  template: `<App/>`
})

index.html

<!DOCTYPE html>
<html>
  <head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <title>myvue</title>
  </head>
  <body>
  <div id="app"></div>
  <!-- built files will be auto injected -->
  </body>
</html>

App.vue

<template>
  <div id="app">
    <head/>
    <hello/>
    <router-link to="/Java">Java</router-link>
    <router-link to="/Python">Python</router-link>
    <router-link to="/Go">Go</router-link>
    <router-view/>
  </div>
</template>

<script>
import head from "./components/head";

import Head from "./components/head";
export default {
  name: 'App',
  components: {
    head,
    hello: {
      template: `<h1>Hello,Vue Designer!</h1>`
    }
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

router.js

//Vue standard
import Vue from "vue";
import VueRouter from "vue-router";

import Java from "../components/Java";
import Python from "../components/Python";
import Go from "../components/Go";

Vue.use(VueRouter)

export default new VueRouter({
  //There is a parameter, routes, which contains an array
  routes: [
    {
      path: "/Java",
      component: Java
    },
    {
      path: "/Python",
      component: Python
    },
    {
      path: "/Go",
      component: Go
    }
  ]
})

Java.vue

<template>
    <h1>Java</h1>
</template>

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

<style scoped>

</style>

Python.vue

<template>
    <h1>Python</h1>
</template>

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

<style scoped>

</style>

Go.vue

<template>
    <h1>Go</h1>
</template>

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

<style scoped>

</style>

13 Vue+ElementUI

problem

cnpm install sass-loader@6 --save-dev
# Create project
vue init webpack ElementUI
# Installation dependency
npm install
# Installing Vue router
npm install vue-router --save-dev
# Installing element UI
npm i element-ui -S
# Installing the SASS loader
cnpm install sass-loader node-sass --save-dev
# Start test
npm run dev	
  • npm install moduleName: install the module into the project directory
  • npm install -g moduleName: - g means to install the module globally. The specific location of the module depends on the location of npm config prefix
  • npm install moduleName -save: - save means to install the module in the project directory and write the dependencies in the dependencies node of the package file, - S is the abbreviation of this command
  • NPM install modulename - save dev: – save dev means to install the module in the project directory and write dependencies in the devdependences node of the package file, - D is the abbreviation of this command

After the creation is successful, open it with idea, delete the net things, and create views and router folders to store views and routes

main.js

import Vue from 'vue'
import App from './App'
//Scan routing configuration
import router from './conter/conter'
//Import elementUI
import ElementUI from "element-ui"
//Import element css
import 'element-ui/lib/theme-chalk/index.css'

Vue.use(router);
Vue.use(ElementUI)

new Vue({
  el: '#app',
  router,
  render: h => h(App),//The ElementUI specifies this
})

App.vue

<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>
<script>
  export default {
    name: 'App',
  }
</script>
<style>

</style>

Main.vue

<template>
  <div>
    <el-container>
      <el-aside width="200px">
        <el-menu :default-openeds="['1']">
          <el-submenu index="1">
            <template slot="title"><i class="el-icon-caret-right"></i>user management </template>
            <el-menu-item-group>
              <el-menu-item index="1-1">
                <!--Where to insert-->
                <router-link v-bind:to="{name: 'Address', params: {address: 'Chongqing University of Posts and Telecommunications'}}">address</router-link>
              </el-menu-item>
              <el-menu-item index="1-2">
                <!--Where to insert-->
                <router-link to="/username">name</router-link>
              </el-menu-item>
            </el-menu-item-group>
          </el-submenu>
          <el-submenu index="2">
            <template slot="title"><i class="el-icon-caret-right"></i>Content management</template>
            <el-menu-item-group>
              <el-menu-item index="2-1">Classification management</el-menu-item>
              <el-menu-item index="2-2">Content list</el-menu-item>
            </el-menu-item-group>
          </el-submenu>
        </el-menu>
      </el-aside>

      <el-container>
        <el-header style="text-align: right; font-size: 12px">
          <el-dropdown>
            <i class="el-icon-setting" style="margin-right: 15px"></i>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>
                <router-link to="/login">User login</router-link>
              </el-dropdown-item>
              <el-dropdown-item>Log out</el-dropdown-item>
            </el-dropdown-menu>
            <span>welcome,{{username}}</span>
          </el-dropdown>
        </el-header>
        <el-main>
          <!--Show the view here-->
          <router-view />
        </el-main>
      </el-container>
    </el-container>
    <el-footer>Footer</el-footer>
  </div>
</template>
<script>
  import Address from "./user/Address";
  export default {
    name: "Main",
    props:{
      username: String
    }
  }
</script>
<style scoped lang="scss">
  .el-header{
    background-image: linear-gradient(160deg, #0093E9 0%, #80D0C7 100%);
    color: #30784a;
    line-height: 60px;
  }
  .el-aside {
    font-family: "Helvetica Neue",Helvetica,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","Microsoft YaHei ",Arial,sans-serif;
    color: #333;
  }
  .el-main{
    background-color: white;
  }
  .el-footer{
    background-image: linear-gradient(160deg, #0093E9 0%, #80D0C7 100%);
    color: #30784a;
    line-height: 60px;
  }
</style>

Login.vue

<template>
  <div class="app">
    <el-form ref="loginForm" :model="form" :rules="rules" label-width="80px" class="login-box">
      <h3 class="login-title">Welcome to login</h3>
      <el-form-item label="account number" prop="username">
        <el-input type="text" placeholder="Please enter the account number" v-model="form.username"/>
      </el-form-item>
      <el-form-item label="password" prop="password">
        <el-input type="password" placeholder="Please input a password" v-model="form.password"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" v-on:click="onSubmit('loginForm')">Sign in</el-button>
      </el-form-item>
    </el-form>

    <el-dialog
      title="reminder"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose">
      <span>Please enter your account and password</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">determine</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: "Login",
    data() {
      return {
        form: {
          username: '',
          password: ''
        },

        // For form validation, you need to add prop attribute in El form item element
        rules: {
          username: [
            {required: true, message: 'Account number cannot be empty', trigger: 'blur'}
          ],
          password: [
            {required: true, message: 'Password cannot be empty', trigger: 'blur'}
          ]
        },

        // Dialog box display and hide
        dialogVisible: false
      }
    },
    methods: {
      onSubmit(formName) {
        // Bind validation function for form
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // Using Vue router to route to the specified page is called programmatic navigation
            this.$router.push("/main/"+this.form.username);
          } else {
            this.dialogVisible = true;
            return false;
          }
        });
      }
    }
  }
</script>

<style lang="scss" scoped>
  .login-box {
    border: 1px solid #DCDFE6;
    width: 350px;
    margin: 180px auto;
    padding: 35px 35px 15px 35px;
    border-radius: 5px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    box-shadow: 0 0 25px #909399;
  }

  .login-title {
    text-align: center;
    margin: 0 auto 40px auto;
    color: #303133;
  }
</style>

Address.vue

<template>
    <h1>address:{{address}}</h1>
</template>

<script>
    export default {
        name: "Address",
        props: {
          address:String
        }
    }
</script>

<style scoped>

</style>

Username.vue

<template>
    <h1>user name</h1>
</template>

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

<style scoped>

</style>

Routing configuration

import Vue from "vue";
import Router from "vue-router";
import Main from "../view/Main";
import Login from "../view/Login";
import Address from "../view/user/Address";
import Username from "../view/user/Username";

Vue.use(Router);

export default new Router({
  mode: "history",
  routes: [
    {
      path: '/main/:username',
      props:true,
      component: Main,
      //Set nested routes
      children: [
        {
          path: "/address/:address",
          props: true,
          name :'Address',
          component: Address
        },
        {
          path: "/username",
          component: Username
        }
      ]
    },
    {
      path: '/login',
      component: Login
    },
    //Set master page
    {
      path: "/",
      component: Main
    }
  ]
});

14 parameter transfer

14.1 method transmission parameters

Method followed by parameter

this.$router.push("/main/"+this.form.username);

Let the router receive

{
  path: '/main/:username',
  props:true,
  component: Main,
  //Set nested routes
  children: [
    {
      path: "/address/:address",
      props: true,
      name :'Address',
      component: Address
    },
    {
      path: "/username",
      component: Username
    }
  ]
},

Use parameters

<span>welcome,{{username}}</span>
<script>
  import Address from "./user/Address";
  export default {
    name: "Main",
    props:{
      username: String
    }
  }
</script>

14.2 label transfer reference

Transfer parameters

<router-link v-bind:to="{name: 'Address', params: {address: 'Chongqing University of Posts and Telecommunications'}}">address</router-link>

Address must be named

{
  path: "/address/:address",
  name :'Address',
  component: Address
},

Turn on parameter transfer

{
  path: "/address/:address",
  props: true,
  name :'Address',
  component: Address
},

Use parameters

<template>
    <h1>address:{{address}}</h1>
</template>

<script>
    export default {
        name: "Address",
        props: {
          address:String
        }
    }
</script>

15 redirection

{
  path: "/goHome",
  redirect:"/"
}

16 404 pages

notFound.vue

<template>
    <h1>Page lost!</h1>
</template>

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

<style scoped>

</style>

Routing configuration

{
  path: "*",
  component: notFound
}

17 routing hook

17.1 general usage

Change Address.vue

<template>
    <h1>address:{{address}}</h1>
</template>

<script>
    export default {
      name: "Address",
      props: {
        address: String
      },
      beforeRouteEnter: (to, from, next) => {
        console.log("Enter the personal information page");
        next();
      },
      beforeRouteLeave: (to, from, next) => {
        console.log("Leave the personal information page");
        next();
      }
    }
</script>

Parameter Description:

  • To: route information to jump
  • from: path information before path jump
  • next: control parameters of the route
  • next() jumps to the next page
  • next('/ path') changes the direction of the route to jump to another route
  • next(false) returns to the original page
  • Next ((vm) = > {}) is only available in beforeRouteEnter. vm is a component instance

17.2 using Axios

#Installing Axios
cnpm install axios --save
cnpm install --save vue-axios

main.js references Axios

import VueAxios from 'vue-axios'
import axios from "axios";

Vue.use(VueAxios,axios);

Prepare data: only the files in our static directory can be accessed, so we put the static files in this directory.
The data is the same as the json data used before. You need to go to the axios example above

<template>
    <h1>address:{{address}}</h1>
</template>

<script>
    export default {
      name: "Address",
      props: {
        address: String
      },
      beforeRouteEnter: (to, from, next) => {
        console.log("Enter the personal information page");
        next(vm => {
          vm.getData()
        });
      },
      beforeRouteLeave: (to, from, next) => {
        console.log("Leave the personal information page");
        next();
      },
      methods: {
        getData: function () {
          this.axios({
            method: 'get',
            url: 'http://localhost:8080/static/mock/data.json'
          }).then(function (response) {
            console.log(response)
          })
        }
      }
    }
</script>

<style scoped>

</style>

Tags: Front-end Vue.js elementUI

Posted on Sat, 20 Nov 2021 12:00:53 -0500 by rantsh