VUE quick start

VUE learning document

Review:

1. What is the relationship between ES6, ES and JS

2,var,let,const

3. String function

  • indexOf

  • lastIndexOf

  • charAt

  • substr

  • substring

  • concat

  • includes

  • startswith

  • endswith

  • The template string will be displayed in whatever format it is written in

4. Deconstruction expression: assign the value of the array or the attribute of the object to the variable

5. Function abbreviation: arrow function

​ var print1 = a => a+b

​ var print2 = (a,b) => { console.log(a); console.log(b) }

6. Shorthand for methods in objects

​ let person = {

​ name:"xxx",

​ eat1:function(food){},

​ eat2(food){},

​ eat3: food => {}

​ }

2021.10.26 summary

1 Vue is an MVVM framework. What is MVVM,

MVVM is an upgrade of MVC. MVVM has a two-way binding more than MVC

2 what is bidirectional binding?

  • If you modify the data, the page will change automatically
  • Modifying the page will also synchronize to the data

3. What are the instructions in Vue?

  • v-for
  • v-model
  • v-bind
  • v-show
  • v-if
  • v-text
  • v-html
  • v-on
  • {interpolation expression

4. What are the hook functions for the Vue lifecycle?

  • beforeCreate: before creating
  • Created: created (!!!)
  • beforeMount: before bidirectional binding
  • Mounted: bidirectional binding completed (!!!)
  • beforeUpdate: before update
  • Updated: the update is complete
  • Before destruction: Before destruction
  • Destroyed: destruction completed

5. What is the bubbling event of js? (this is a problem that needs to be solved)

  • When an event occurs, the event will begin to propagate (from inside to outside or from outside to inside), which will trigger the methods of all parent or child layers
  • Solution: use the event modifier. stop

6. Calculated attribute computed

7. watch does something when the value of a property changes

0 target

  1. Vue basic syntax
    • Vue's instructions
    • Animation of Vue
    • Components of Vue
    • Vue routing
    • Component lifecycle in Vue
    • Launching Ajax data requests using axios in Vue
  2. Vue project

1. Preface

Development of front-end development mode.

Static page

  • The original web page is mainly HTML, which is a pure static web page. The web page is read-only, and the information flow can only flow one way from the service to the client. Developers only care about the style and content of the page.

Asynchronous refresh, DOM operation

  • In 1995, Netscape engineer Brendan Eich spent 10 days designing JavaScript language

    With the birth of JavaScript, we can manipulate the DOM elements and styles of the page. The page has some dynamic effects, but it is still static.

  • ajax prevalence:

    • Since 2005, ajax has been paid more and more attention by front-end developers, because the data and rendering effect of the page can be updated without refreshing the page.
    • At this time, developers should not only write HTML styles, but also understand the interaction between ajax and the back end, and then operate Dom elements through JS to achieve page dynamic effects. Popular frameworks such as Jquery are typical examples.

MVVM, focusing on models and views - equivalent to the MVC on the back end, but the MVVM on the front end is more powerful than MVC

  • In 2008, google's Chrome was released, and then it occupied the market at a very fast speed, surpassing IE to become the leader of the browser market.

  • In 2009, Ryan Dahl built an asynchronous IO framework based on event loop: Node.js on the basis of Google's Chrome V8 engine.

    • Asynchronous IO based on time cycle
    • Single thread operation to avoid multi-threaded variable synchronization
    • JS can write background diamante and unified programming language for front and rear platforms
  • The greatness of node.js is not to make JS move towards back-end development, but to build a huge ecosystem.

  • In 2010, NPM was first released as the package management system of node.js. Developers can follow the Common.js specification to write the node.js module, and then publish it to NPM for other developers to use. At present, it is the world's largest package module management system.

  • Subsequently, a large number of front-end frameworks emerged on the basis of node:

    [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-mhT4qeTc-1637151833109)(assets/1525825983230.png)]

MVVM mode

  • M: That is, Model, including data and some basic operations
  • 5: That is, View, page rendering results
  • VM: view model, two-way operation between model and view (without developer intervention)

Before MVVM, developers obtain the required data Model from the back end, and then render the Model into the View through DOM operation. Then, when the user operates the View, we also need to obtain the data in the View through the DOM, and then synchronize it to the Model.

What the VM in MVVM needs to do is to completely encapsulate the DOM operation. Developers no longer need to care about how the Model and View affect each other:

  • As long as our Model changes, it will naturally appear on the View.
  • When the user modifies the View, the data in the Model will also change.

Liberate developers from cumbersome DOM operations and focus on how to operate the Model.

Note: all operations of getting page elements or assigning values to page elements are DOM operations

[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-PeLWi8RY-1637151833112)(assets/1525828854056.png)]

What we want to learn today is a framework of MVVM pattern: Vue

Interview question 1: explain MVVM?

M: model data layer

5: V iew view layer

VM: the layer that binds the model layer and the view layer together. This layer vue has been completed automatically

Interview 2: what is the difference between MVC and MVVM?

Before MVVM, developers obtain the required data Model from the back end, and then render the Model into the View through DOM operation. Then, when the user operates the View, we also need to obtain the data in the View through the DOM, and then synchronize it to the Model.

What the VM in MVVM needs to do is to completely encapsulate the DOM operation. Developers no longer need to care about how the Model and View affect each other:

  • As long as our Model changes, it will naturally appear on the View.
  • When the user modifies the View, the data in the Model will also change.

2. Recognize Vue

Vue (pronunciation / vju) ː/, Similar to view) is a progressive framework for building user interfaces. 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 or existing projects. On the other hand, when with Modern tool chain And various Support class library When used in combination, Vue can also provide drivers for complex single page applications.

Progressive:

1 we can use vue just like jQuery – familiar with the basic syntax of vue

2. Use vue in the way of node - enterprise development mode - Master vue enterprise development mode

The three giants of front-end framework: vue.js (155k), React.js (118k) and AngularJS (45k). Vue.js is famous for its lightweight and easy-to-use. Vue.js and React.js are developing fastest. AngularJS is the third and continues to decline.

Official website: https://cn.vuejs.org/

reference resources: https://cn.vuejs.org/v2/guide/

[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-81dtDdf5-1637151833113)(assets/1525829249048.png)]

Git address: https://github.com/vuejs

[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-9Jwc8LEm-1637151833116)(assets/1525829030730.png)]

You Yuxi, creator of Vue.js and founder of Vue Technology, is committed to the research and development of Vue.

Summary:

1 vue is an mvvm framework, which is the back-end MVC framework, but it has more powerful functions

2 vue's most comprehensive document is the official document

3 vue it's hot now

3. Quick start

Next, we quickly appreciate the charm of vue

3.1. Create project

Create a maven project:

[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-VAx7huFd-1637151833117)(assets/1540849476886.png)]

Location information:

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-C2mmqa1V-1637151833118)(assets/1540805852428.png)]

3.2. Installation vue

3.2.1. Download and install

Download address: https://github.com/vuejs/vue

​ https://github.com/vuejs/vue/blob/dev/dist/vue.js

You can download version 2.6.10 https://github.com/vuejs/vue/archive/v2.6.10.zip

Download and unzip to get the vue.js file.

3.2.2. Using CDN

Or you can directly use the public CDN service:

<!-- Development environment version, including command line warnings with help -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

Or:

<!-- Production environment version, optimized size and speed -->
<script src="https://cdn.jsdelivr.net/npm/vue"></script>

3.3.vue introduction case

3.3.1.HTML template

Create a new HTML in the Vue demo directory

[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-0BAzOBNl-1637151833118)(assets/1540826222003.png)]

In hello.html, we write a simple code:

[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-VvF1w750-1637151833119)(assets/1540826264564.png)]

h2 to output a sentence: xx is very handsome. The renderings are as follows:

[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-8pWjA7ed-1637151833120)(assets/1540870582069.png)]

3.3.2.vue rendering

Then we render through Vue:

<!-- introduce vue -->
<script src="vue-2.6.10.js"></script>
<!-- 1 Must have parent container,All content can only be written in this parent container
      The parent container must have id Properties, id The value of is user-defined, but it is generally called app
 -->
<div id="app">

    <!-- Here you need to get Vue Object name
         {{}}Two braces get data The value of the property in
     -->
    <h2>{{name}}Very handsome</h2>
    <h2>have{{num}}A goddess fell for it</h2>
</div>
<!-- adopt vue control x Content displayed -->
<script>
    // Direction 1: when the data. Attribute content is changed, it will be automatically updated in the view
    // Direction 2: when the name is changed on the page, the name in data will be updated automatically
    var vm = new Vue({
        el:"#app",//el is the abbreviation of element, pointing to the id of the parent container
        data:{// Data is specially used to store data
            name:"Chico ",
            num:100
        }
    });


</script>
  • First, create a Vue instance through new Vue()
  • Then the constructor receives an object with some properties:
    • el: is the abbreviation of element. Select the page element to be rendered by id. in this case, it is a div
    • Data: data. Data is an object with many attributes that can be rendered to the view
      • Name: Here we specify a name attribute
  • In the h2 element in the page, we render the name attribute just defined by {name}}.

Open the page to view the effect:

[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-5qkQPoxN-1637151833121)(assets/1540826329204.png)]

What's more amazing is that when you modify the name attribute, the page will change:

[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-CRhhYgtS-1637151833122)(assets/1540826396782.png)]

3.3.3. Bidirectional binding

Direction 1: when changing data The value of the property in the page will also change
 Direction 2: when changing the content of the page text box, data The value in will also change automatically
       input Text box

Let's make a simple modification to the case just now:

<div id="app">
    <input type="text" v-model="num">
    <h2>
        {{name}} Very handsome,
        have{{num}}A goddess was fascinated by him.
    </h2>
</div>
<script src="vue-2.6.10.js"></script>
<script type="text/javascript">
    // Generate a Vue instance
    var app = new Vue({
        el:"#app", // el, i.e. element. Page elements to render
        data:{ // data
            name:"Chico ",
            num:1
        }
    })
</script>
  • We added a new attribute to data: num
  • There is an input element in the page, which is bound to num through v-model.
  • At the same time, output on the page through {{num}}

effect:

[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-Ejl9zy1I-1637151833123)(assets/1540826774926.png)]

We can observe that the change of input box causes the change of num in data, and the page output also changes.

  • Input is bound to num, and the value of input changes, affecting the value of num in data
  • The page {{num}} is bound to the data num, so the change of num value causes the change of page effect.

There is no dom operation, which is the charm of two-way binding.

3.3.4. Event handling

We add a button to the page:

<input type="button" value="+" v-on:click="num++">
<input type="button" value="-" v-on:click="num--">
  • Here, the click event is bound with the v-on instruction instead of the ordinary onclick, and then the num is directly operated
  • Normal click cannot directly operate num.

effect:

[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-Z93wPc3Y-1637151833124)(assets/1540845305380.png)]

4.Vue instance

4.1. Create Vue instance

Each Vue application starts by creating a new Vue instance with the Vue function:

var vm = new Vue({
  // option
})

Pass in an object in the constructor, and declare various data and methods required by Vue in the object, including:

  • el
  • data
  • methods
  • ...

wait

Next, let's introduce them one by one.

4.2. Template or element

Each Vue instance needs to be associated with an Html template, and Vue will render the view based on this template.

We can specify it through the el attribute.

For example, an html template:

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

Then create a Vue instance and associate the div

var vm = new Vue({
	el:"#app"
})

In this way, Vue can render based on the div element with id app as a template. The Vue feature cannot be used outside this div range.

4.3. Data

When a Vue instance is created, it will try to obtain all the attributes defined in data for view rendering, and monitor the attribute changes in data. When the data changes, all relevant views will be re rendered, which is a "responsive" system.

html:

<div id="app">
    <input type="text" v-model="name"/>
</div>

js:

var vm = new Vue({
    el:"#app",
    data:{
        name:"Lau Andy"
    }
})
  • The change of name will affect the value of input
  • The value entered in input will also cause the name in vm to change

4.4. Method

In Vue instances, in addition to defining data attributes, methods can also be defined and used within the scope of Vue.

html:

<div id="app">
    {{num}}
    <button v-on:click="add">plus</button>
</div>

js writing method 1:

<div id="app">
    {{num}}
    <button v-on:click="add">plus</button>
</div>
<script src="vue-2.6.10.js"></script>
<script>
    var vm = new Vue({
       el:"#app",
       data:{
           num:0
       },
       methods:{
           add:function(){
               this.num++;
           }
       }
    });
</script>

js writing method 2:

<div id="app">
    {{num}}
    <button v-on:click="add">plus</button>
</div>
<script src="vue-2.6.10.js"></script>
<script>
    var vm = new Vue({
       el:"#app",
       data:{
           num:0
       },
       methods:{
           add(){
               this.num++;
           }
       }
    });


</script>

4.5. Life cycle hook function

Review: the life cycle of servlet s – life and death

4.5.1. Life cycle

When each Vue instance is created, it goes through a series of initialization processes: creating an instance, loading a template, rendering a template, and so on. Vue sets a hook function (listener function) for each state in the lifecycle. Each time a Vue instance is in a different lifecycle, the corresponding function is triggered.

Life cycle:

[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-VhOcMqmB-1637151833124)(assets/lifecycle.png)]

[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-Ayb3Ggbf-1637151833125)(assets/1540850010193.png)]

Life cycle process: – each process corresponds to a function. When vue is in a certain stage, the function of that stage will be triggered automatically

1 before initialization -- BeforeCreate

2 initialization complete - send ajax --created

3. Before bidirectional data binding / mounting - BeforeMount

4. Bidirectional data binding completed / mounting completed -- Mounted

5 before update -- BeforeUpdate

6 update completed – updated

7 before destruction – BeforeDestroy

8 destruction completed – Destroyed

4.5.2. Hook function

  • Example 1: created means after the vue instance is created;

We can define a created function in Vue to represent the constructor of this period:

html:

<div id="app">
    {{hello}}
</div>

js:

<script src="vue-2.6.10.js"></script>
<script>
    var vm = new Vue({
       el:"#app",
       data:{
           hello:''
       },
       created(){
           this.hello = 'czdx,Unify the Jianghu for generations'
       }
    });
</script>

result:

[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-nylJtOms-1637151833126)(assets/1540845983254.png)]

  • Example 2:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script src="vue-2.6.10.js"></script>

<div id="app">
    {{msg}}

</div>
<script>
    var vm = new Vue({
       el:"#app",
       data:{
           msg:'Chuanzhi University will unify the Jianghu for generations'
       },
       methods:{

       },
       // Before creation
       beforeCreate(){
            showData("Before creation",this);
       },
       created(){
           showData("Creation complete",this);
       },
       // Before bidirectional data binding
       beforeMount(){
           showData("Before bidirectional data binding",this)
       },
       // Bidirectional data binding completed
       mounted(){
           showData("Bidirectional data binding completed",this)
       },
       beforeUpdate(){
           showData("Before update",this)
       },
       updated(){
           showData("Update complete",this)
       },
       beforeDestroy(){
           showData("Before destruction",this)
       },
       destroyed(){
           showData("Destruction complete",this)
       }



    });
    // Print the words "before creation"
    // Print msg value
    // Print the content in div of page id=app
    // First parameter: before creation, after destruction
    function showData(process,obj){
        console.log(process);
        console.log(obj.msg);
        console.log(document.getElementById("app").innerHTML)
        console.log("----------------------------------")
    }
    // Update data
    //vm.msg="good. good study   day  day  up."
    // Destroy data
    vm.$destroy();
</script>
</body>
</html>

Summary:

Vue's life process is very rich, and each process has something to complete

2. Created life cycle: vue has been created and data is available - > to the background through ajax

The next operation is bidirectional data binding

4.5.3.this

We can see who the this variable in vue is. When we create it, we print this

var vm = new Vue({
    el:"#app",
    data:{
        hello: '' // hello initialization is null
    },
    created(){
        this.hello = "czdx,Unify the Jianghu for generations";
        console.log(this);
    }
})

Console output:

[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-C0QLdp6V-1637151833127)(assets/1540846042618.png)]

Summary:

this represents the current vue object

5. Instructions

What are instructions?

Directives are with   v-   Special characteristics of prefixes. The expected value of the instruction attribute is a single JavaScript expression. The responsibility of the instruction is to act on the DOM responsively when the value of the expression changes.

For example, the v-model, v-on... In our introductory case are all instructions.

5.1. Interpolation expression

5.1.1. Braces

Format:

{{expression}}

explain:

  • The expression supports JS syntax and can call JS built-in functions (there must be a return value)
  • The expression must have a return result. For example, 1 + 1, expressions without results are not allowed, such as var a = 1 + 1;
  • You can directly obtain the data or functions defined in the Vue instance

Example:

HTML:

<div id="app">{{name}}</div>

JS:

var app = new Vue({
    el:"#app",
    data:{
        name:"Chico "
    }
})

5.1.2. Interpolation flashing

Using {}} will cause problems when the network speed is slow. When the data is not loaded, the original {}} will be displayed on the page, and the correct data will be displayed only after loading, which is called interpolation flicker.

Let's slow down the network speed and try the case just now:

[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-2Gb38lzu-1637151833127)(assets/1525843894502.png)]

Refresh page:

[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-tjT0fjaH-1637151833128)(assets/1540846239485.png)]

5.1.3.v-text and v-html

Use the v-text and v-html instructions instead of {}

Function: it is used for data presentation. It can replace {} and effectively solve the flicker problem of interpolation expression

explain:

  • v-text: output the data to the inside of the element. If the output data has HTML code, it will be output as normal text
  • v-html: output the data to the inside of the element. If the output data has HTML code, it will be rendered

Example:

HTML:

<div id="app">
    <span v-text="hello"></span><br>
    <span v-html="hello"></span>

</div>

JS:

var vm = new Vue({
       el:"#app",
       data:{
           hello:'Hello, I'm Chico'
       }
    });

effect:

[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-UGhCSw1X-1637151833129)(assets/1540846508928.png)]

And there will be no interpolation flicker. When there is no data, it will display blank.

5.2.v-model

The interpolation expression, v-text and v-html just now can be regarded as one-way binding. The data affects the View rendering, but not the other way around. Next, the v-model learned is a two-way binding, and views and models will affect each other.

Since it is a two-way binding, you must be able to modify data in the view, which limits the element type of the view. Currently, the available elements of v-model are:

  • input-text
  • input-password
  • select
  • textarea
  • checkbox
  • radio
  • Components (custom components in Vue)

Basically, except for the last item, everything else is the input item of the form.

5.2.1 input

Html:

<div id="app">
    <input type="text" v-model="num">
    <h2>{{num}}</h2>
    <input type="button" value="+" v-on:click="num++">
    <input type="button" value="-" v-on:click="num--">
</div>

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

</script>

effect:

[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-G8GnyUgP-1637151833130)(assets/1540850906295.png)]

5.2.2 checkbox

html:

<div id="app">
    <input type="checkbox" v-model="language" value="Java" />Java<br/>
    <input type="checkbox" v-model="language" value="PHP" />PHP<br/>
    <input type="checkbox" v-model="language" value="Swift" />Swift<br/>
    <h1>
        You chose:{{language.join(',')}}
    </h1>
</div>
<script src="./node_modules/vue/dist/vue.js"></script>
<script type="text/javascript">
    var vm = new Vue({
        el:"#app",
        data:{
            language: []
        }
    })
</script>
  • When multiple checkboxes correspond to a model, the type of model is an array, and the value of a single checkbox is of boolean type
  • The value corresponding to radio is the value of input
  • By default, the model corresponding to input and textarea is a string
  • select single selection corresponds to a string, and multiple selection corresponds to an array

effect:

[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-1UNrnwZA-1637151833131)(assets/1525845481512.png)]

5.2.3 radio

html:

<div id="app">
    <input type="radio" value="male" v-model="sex">male
    <input type="radio"  value="female" v-model="sex">female
    <h2>{{sex}}</h2>
</div>

<script src="vue-2.6.10.js"></script>
<script>
    var vm = new Vue({
       el:"#app",
       data:{
           sex:'male'
       }
    });
</script>

effect:

[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-GbqUf5PT-1637151833131)(assets/1540851397148.png)]

5.2.4 textarea

html:

<div id="app">
    <input type="radio" value="male" v-model="sex">male
    <input type="radio"  value="female" v-model="sex">female
    <h2>{{sex}}</h2>
    <textarea v-model="sex"></textarea>
</div>

<script src="vue-2.6.10.js"></script>
<script>
    var vm = new Vue({
       el:"#app",
       data:{
           sex:'male'
       }
    });
</script>

effect:

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-nNGk4KWH-1637151833132)(assets/1540851457369.png)]

5.2.5 select – you need to combine attribute binding v-bind and loop v-for

html:

<div id="app">
    <input type="radio" value="male" v-model="sex">male
    <input type="radio"  value="female" v-model="sex">female
    <h2>{{sex}}</h2>
    <textarea v-model="sex"></textarea><br>
    <select v-model="favor">
        <option v-for="item in items" :value="item">{{item}}</option>
    </select>


</div>

<script src="vue-2.6.10.js"></script>
<script>
    var vm = new Vue({
       el:"#app",
       data:{
           sex:'male',
           favor:'play the piano',
           items:['sing','dance','play the piano']
       }
    });
</script>

effect:

5.3.v-on

5.3.1v-on: click basic usage, abbreviated @ Click

The v-on instruction is used to bind events to page elements. Syntax:

v-on:Event name="js Fragment or function name"

Example:

<div id="app">
    <!--Write directly in event js fragment-->
    <button v-on:click="num++">increase</button><br/>
    <!--Event specifies a callback function, which must be Vue Functions defined in the instance-->
    <button v-on:click="decrement">reduce</button><br/>
    <h1>num: {{num}}</h1>
</div>
<script src="vue-2.6.10.js"></script>
<script type="text/javascript">
    var app = new Vue({
        el:"#app",
        data:{
            num:1
        },
        methods:{
            decrement(){
                this.num--;
            }
        }
    })
</script>

effect:

[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-eBpYs1cu-1637151833133)(assets/5.gif)]

In addition, event binding can be abbreviated. For example, v-on:click='add 'can be abbreviated as @ click='add'

5.3.2 v-on:keydown

Indicates a keyboard press event.

http://tool.oschina.net/commons?type=4

ascii code

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-Yg2lGms5-1637151833133)(assets/wps3830.tmp.jpg)]

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script src="vue-2.6.10.js"></script>
<div id="app">
    <input type="text" v-model="name" v-on:keydown="show($event)">

</div>
<script>
    new Vue({
        el:"#app",
        data:{
            name:""
        },
        methods:{
            show(e){
                var keyCode = e.keyCode;
                console.log(keyCode)
            }
        }

    })


</script>

</body>
</html>

5.3.3 v-on:mouseover and v-on: mouseout

Mouse in and out event area events

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script src="vue-2.6.10.js"></script>
<div id="app">
    <div style="width: 100px;height: 100px; border: 1px solid red" @mouseover="show()" @mouseout="go()">

    </div>

</div>
<script>
    new Vue({
        el:"#app",
        data:{
            name:""
        },
        methods:{
            show(){
                console.log("Come in")
            },
            go(){
                console.log("Come out")
            }
        }

    })


</script>

</body>
</html>

5.3.4 js bubbling - a problem that needs to be addressed

[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-WCpTmZGw-1637151833135)(assets/1540937357720.png)]

Concept:

When an event occurs, the event will begin to propagate (from inside to outside or from outside to inside), which will trigger the methods of all parent or child layers

Case:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script src="vue-2.6.10.js">
</script>
<div id="app">
    <div style="width: 100px;height: 100px; border: red 1px dashed"
           @mouseover="over()" @mouseout="out()">

        <textarea @mouseover="myover($event)"></textarea>

    </div>

</div>
<script>
    var vm = new Vue({
       el:"#app",
       methods:{
           over(){
               console.log("Come in")
           },
           out(){
               console.log("I'm out")
           },
           myover(e){
               console.log("get into txt Yes");
               // Solution of bubbling in js
               // Prevent the propagation of events
               e.stopPropagation();
           }

       }

    });

</script>

</body>
</html>

5.3.5 event modifier – solution to bubbling and other problems in vue

Vue.js provides event modifiers for v-on to handle DOM event details, such as event.preventDefault() or event.stopPropagation().

Vue.js calls the modifier through the instruction suffix represented by the dot (.).
. stop / / stop triggering and prevent bubble modifier

. prevent / / prevent the event from happening. The default behavior of the event is to prevent the event from happening
. capture / / capture
. self / / only click on yourself to run
. once / / execute only once

[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-YQou8GxS-1637151833136)(assets/1540956546945.png)]

Case 1:

<script src="vue-2.6.10.js">
</script>
<div id="app">
    <div style="width: 100px;height: 100px; border: red 1px dashed"
           @mouseover="over()" @mouseout="out()">

        <textarea @mouseover.stop="myover($event)"></textarea>
        
        <form @submit.prevent action="http://www.czxy.com">
            <input type="submit" value="Submit">
        </form>
    </div>

</div>
<script>
    var vm = new Vue({
       el:"#app",
       methods:{
           over(){
               console.log("Come in")
           },
           out(){
               console.log("I'm out")
           },
           myover(e){
               console.log("get into txt Yes");
               // Solution of bubbling in js
               // Prevent the propagation of events
               //e.stopPropagation();
           }

       }

    });

</script>

Case 2:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script src="vue-2.6.10.js"></script>
<div id="app">
    <form @submit.prevent action="http://www.czxy.com">
        <input type="submit" value="Submit">
    </form>

</div>
<script>
    new Vue({
        el:"#app",
        data:{
            name:""
        },
        methods:{
        }

    })


</script>

</body>
</html>

5.3.6 key modifier

Vue allows you to add key modifiers for v-on when listening for keyboard events

All key aliases:

.enter  // Represents the enter key of the keyboard
.tab
.delete (capture "delete" and "Backspace" key)
.esc
.space
.up
.down
.left
.right
.ctrl
.alt
.shift
.meta

Case:

<script src="vue-2.6.10.js"></script>

<div id="app">
    <!-- Press any key at will ascii code -->
<input type="text" @keydown="show($event)">
    <br>
    <!-- Judge whether it is enter key -->
<input type="text" @keydown.13="show($event)"><br>
    <!-- Judge whether it is enter key -->
<input type="text" @keydown.enter="show($event)">
    </div>

<script>
    var vm = new Vue({
        el:"#app",
        methods:{
            show(e){
                console.log(e.keyCode)
            }
        }
    });
</script>

Job 1: only 0-9 numbers are allowed in the text box

5.4.v-for

Traversing the data rendering page is a very common requirement, which is implemented through the v-for instruction in Vue.

5.4.1. Traversing array

Syntax:

v-for="item in items"
  • items: the array to be traversed needs to be defined in vue's data.
  • item: alias of array element obtained by iteration

Example: ul display

<div id="app">
    <ul>
        <li v-for="user in users">
            {{user.name}} : {{user.gender}} : {{user.age}}
        </li>
    </ul>

</div>
<script src="vue-2.6.10.js"></script>
<script>
    var vm = new Vue({
       el:"#app",
       data:{
           users:[
               {name:"Zhang San",gender:"male",age:21},
               {name:"Li Si",gender:"male",age:22},
               {name:"WangTwo ",gender:"female",age:23},
               {name:"Zhao Liu",gender:"male",age:24},
               {name:"Sun Qi",gender:"male",age:25}
           ]
       }
    });
</script>

effect:

[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-1gfAwYcl-1637151833136)(assets/1540847621535.png)]

Example: table display

html code:

<table border="1" cellpadding="0" cellspacing="0" width="300" height="200">
    <tr>
        <th>full name</th>
        <th>Gender</th>
        <th>Age</th>
    </tr>
    <tr v-for="user in users">
        <td>{{user.name}}</td>
        <td>{{user.gender}}</td>
        <td>{{user.age}}</td>
    </tr>

</table>

effect:

[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-2TfHX4wc-1637151833137)(assets/1540847963250.png)]

5.4.2. Array subscript

In the process of traversal, if we need to know the array subscript, we can specify the second parameter:

grammar

v-for="(item,index) in items"
  • items: array to iterate
  • item: array element alias obtained by iteration
  • Index: the current element index iterated to, starting from 0.

Example

    <div id="app">
        <ul>
            <li v-for="(user,index) in users">
                {{index}} - {{user.name}} : {{user.gender}} : {{user.age}}
            </li>
        </ul>
    </div>

effect:

[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-P97PSO6I-1637151833138)(assets/1540848062565.png)]

5.5.v-if and v-show

Common ground: it's all conditional judgment

v-if: remove element

v-show: simply add display:none

5.5.1. Basic use

v-if, as the name suggests, conditional judgment. When the result is true, the element will be rendered.

Syntax:

v-if="Boolean expression"

Example:

<script src="vue-2.6.10.js"></script>
<div id="app">
        <input type="button" @click="show = !show" value="Click me to switch">
        <h1 v-if="show">
             Hello
        </h1>

</div>
<script>
    new Vue({
        el:"#app",
        data:{
            show:true
        },
        methods:{
        }

    })
</script>

effect:

[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-sfwMovsI-1637151833138)(assets/ScreenGif-1525850553649.gif)]

5.5.2. Combination with v-for

When v-if and v-for appear together, v-for takes precedence. In other words, it will traverse first and then judge the conditions.

Example: screen out all women of gender

<script src="vue-2.6.10.js"></script>
<div id="app">
    <ul>
        <li v-for="(user,index) in users" v-if="user.gender==='female'">
            {{index}} - {{user.name}} : {{user.gender}} : {{user.age}}

        </li>
    </ul>

</div>
<script>
    new Vue({
        el:"#app",
        data:{
           users:[{name:"tom",gender:"male",age:21},
               {name:"meiei",gender:"male",age:21},
               {name:"lily",gender:"female",age:21},
               {name:"jack",gender:"male",age:21},
               {name:"lucy",gender:"female",age:21}
           ]
        },
        methods:{

        }

    })
</script>

effect:

5.5.3.v-else

You can use the v-else instruction to represent the "else block" of v-if:

<div v-if="Math.random() > 0.5">
  Now you see me
</div>
<div v-else>
  Now you don't
</div>

The v-else element must follow the element with v-if or v-else-if, otherwise it will not be recognized.

v-else-if, as the name suggests, acts as the "else if block" of v-if and can be used continuously:

<div v-if="type === 'A'">
  A
</div>
<div v-else-if="type === 'B'">
  B
</div>
<div v-else-if="type === 'C'">
  C
</div>
<div v-else>
  Not A/B/C
</div>

Similar to v-else, v-else-if must also follow the element with v-if or v-else-if.

5.5.4.v-show

Another option for displaying elements conditionally is the v-show instruction. The usage is roughly the same:

<h1 v-show="ok">Hello!</h1>

The difference is that elements with v-show are always rendered and retained in the DOM. V-show simply switches the CSS attribute display of an element.

Example:

    <div id="app">
        <!--Write directly in event js fragment-->
        <button v-on:click="show = !show">Click switch</button><br/>
        <h1 v-if="show">
            Hello
        </h1>
    </div>
    <script src="vue-2.6.10.js"></script>
    <script type="text/javascript">
        var app = new Vue({
            el:"#app",
            data:{
                show:true
            }
        })
    </script>

code:

[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-cipbrM6T-1637151833139)(assets/1.gif)]

5.6.v-bind

The HTML tag of the page has many attributes. What should I do if I want to get the value of data in vue?

5.6.1. Binding class style

If we want to dynamically modify the attributes of page elements, such as class attribute, it is wrong to write this:

<div class="{{mystyle}}"></div>

Because interpolation expressions cannot be used in the value of attributes.

Case:

    <script src="vue-2.6.10.js"></script>
<div id="app">
    <span v-bind:class="a">Chuanzhi University</span><br>
    <span v-bind:class="b">Chuanzhi University</span><br>
    <span :class="c">Chuanzhi University</span><br>
</div>
<script>
    new Vue({
        el:"#app",
        data:{
            a:"a",
            b:"b",
            c:"c"
        },
        methods:{

        }

    })


</script>
<style>
    .a{
        color: red;
    }
    .b{
        color: yellow;
    } 
    .c{
          color: orchid;
      }

</style>

Class code:

<script src="vue-2.6.10.js"></script>
<div id="app">
    <!--
    Learned instructions
    v-on
    v-model
    v-text
    v-html
    v-for
    v-if
    v-show
    v-else
    {{}}
    -->
    <!-- For the value of the attribute, the interpolation expression cannot be obtained -->
    <!--Wrong way:<a href="{{url}}">Baidu</a><br>-->
    The right way:<a v-bind:href="url">Baidu</a>


    <!-- class Is the attribute of the tag. How does the attribute from vue Get the value from? -->
    <div :class="mydiv"></div>
</div>
<script>
    var vm = new Vue({
        el:"#app",
        data:{
            url:"http://www.czxy.com",
            mydiv:"redDiv"
        }

    });
</script>

<style type="text/css">
    .redDiv{
        width: 100px;
        height: 100px;
        border: 1px solid red;
    }
    .greenDiv{
        width: 100px;
        height: 100px;
        border: 1px solid green;
    }


</style>

5.6.2. Abbreviations

v-bind:class can be abbreviated as: class

  • Comprehensive case: drop down list box to change div style
<script src="vue-2.6.10.js"></script>
<div id="app">
    <!-- When the drop-down list box changes, div Your style will change
         That is, you want to use the newly selected style in the drop-down list box div,That is, give the value to mydiv
     -->
    <select v-model="mydiv">
        <!-- value yes option of HTML attribute  v-for yes vue Instructions, can they access each other directly? A: No -->
        <option v-for="style in myStyles" v-bind:value="style">{{style}}</option>
    </select>

    <!-- class Is the attribute of the tag. How does the attribute from vue Get the value from? -->
    <div :class="mydiv"></div>
</div>
<script>
    var vm = new Vue({
        el:"#app",
        data:{
            mydiv:"redDiv",
            myStyles:['redDiv','greenDiv','blackDiv','yellowDiv'],
            mySelectValue:''
        }

    });
</script>

<style type="text/css">
    .redDiv{
        width: 100px;
        height: 100px;
        background: red;
    }
    .greenDiv{
        width: 100px;
        height: 100px;
        background: green;
    }
    .blackDiv{
        width: 100px;
        height: 100px;
        background: black;
    }
    .yellowDiv{
        width: 100px;
        height: 100px;
        background: yellow;
    }

</style>

5.7. Calculate attribute - it is essentially a method. When it is written, it is a method and when it is used, it is an attribute

It is very convenient to use js expression in interpolation expression, and it is often used.

However, if the content of the expression is very long, it will not be elegant enough, and it is inconvenient to maintain later. For example, in the following scenario, we have a date data that needs to be displayed on the page. The default display method is:

What if you just want to display the year, month and day?

<body>
    <script src="vue-2.6.10.js"></script>
<div id="app">
    {{birthday.getFullYear() +"-" + birthday.getMonth() + "-" +birthday.getDate()}}
</div>
<script>
    new Vue({
        el:"#app",
        data:{
            birthday:new Date()
        },
        methods:{

        }

    })


</script>

Although the results can be obtained, it is very troublesome.

Calculation properties are provided in Vue to replace complex expressions:

<script src="vue-2.6.10.js"></script>
<div id="app">
        Your birthday is: {{birth}}
</div>
<script>
    new Vue({
    el:"#app",
    data:{
        birthday:new Date()
    },
    methods:{

    },
    computed:{
        birth(){
            return this.birthday.getFullYear() +"-" + this.birthday.getMonth() + "-" +this.birthday.getDate();
        }
    }

})
</script>
  • Computing properties is essentially a method, but you must return data. Then, when rendering the page, you can use this method as a variable.

Page usage:

effect:

[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-FfR5KqKT-1637151833140)(assets/1525861635758.png)]

6 VueJS ajax

6.1 axios - js technology for sending ajax

Axios is a promise based HTTP library that can be used in browsers and node.js

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

6.2 introduction of axios

You can use script to import

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

Introduce axios-0.18.0.js

[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-kpcUoVap-1637151833141)(assets/1540940532176.png)]

6.3 cases

6.3.1 get request

// Create a request for the user with the given ID
axios.get('/user?ID=12345')
    .then(function (response) {
    console.log(response);
})
    .catch(function (error) {
    console.log(error);
});

// Alternatively, the above request can do so
axios.get('/user', {
    params: {
        ID: 12345
    }
}).then(function (response) {
    console.log(response);
}).catch(function (error) {
    console.log(error);
});
 

6.3.2 post request

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
}).then(function (response) {
    console.log(response);
}).catch(function (error) {
    console.log(error);
});

For convenience, aliases are provided for all supported request methods

axios.request(config)

axios.get(url[, config])

axios.delete(url[, config])

axios.head(url[, config])

axios.post(url[, data[, config]])

axios.put(url[, data[, config]])

axios.patch(url[, data[, config]])

6.4 Code:

[requirement]: create data/user.json file -- get all users

Use axios to read the contents of the user.json file and output the contents on the page.

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8" />
    <title>vuejs in axios data calling</title>
    <script src="vue-2.6.10.js"></script>
    <script src="axios-0.18.0.js"></script>
</head>

<body>
<div id="app">
    {{message}}
</div>
</body>
<script>
    var vm = new Vue({
        el: "#app",
        data: {
            message: ''
        },
        methods: {
            init: function(){
                axios.get("./data/user.json").then(function(response){
                    // alert(response);
                    alert(JSON.stringify(response))
                    alert(response.data[0].username);
                })
            }
        },
        created: function(){
            this.init();
        }
    });
</script>

</html>

Create the data directory and create user.json

[
  {"username":"Zhang San","age":22},
  {"username":"Li Si","age":21},
  {"username":"Wang Wu","age":20},
  {"username":"Zhao Liu","age":23}
]

[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-20JlFhBj-1637151833142)(assets/wps4EF4.tmp.jpg)]

7 Summary of Vue structure

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../vue-2.6.10.js"></script>
</head>
<body>
<div id="app">

</div>
<script>
    var vm = new Vue({
        el:"#app",
        data:{
            users:[],// Define array
            user:{},//Define object
            username:'',//Define properties of type string
            num:10// Define properties of type int
        },
        methods:{

        },
        created(){

        },
        //Calculation properties
        computed:{

        }


    })


</script>

Keywords: Java MySQL Spring

Added by ParkerPHP on Wed, 17 Nov 2021 14:34:08 +0200