Vue.js learning notes

https://www.bilibili.com/video/BV1SE411H7CY

Review of some js contents

Array related methods

  • length gets the number of elements
  • push add after
  • shift removes the element on the left
  • splice(index,num) deletes elements. Where does index start to delete elements? num is how many elements are deleted

Use js to select elements and bind click events

  • document.querySelector("class name") onclick = function() {code block}

Vue introduction and introduction

Install the plug-ins vetur and Vue 3 Snippets for syntax prompts

<!-- Development environment version with helpful command line warnings -->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!-- Production environment version, optimized size and speed -->
<script src="https://cdn.jsdelivr.net/npm/vue"></script>

It is not recommended for novices to use Vue cli directly, especially when they are not familiar with node based JS build tool.

Several forms of data acquisition

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>first vue program</title>
</head>
<body>
    <div id="app">
        <h3>{{ msg }}</h3>
        <h3>full name:{{ user.name }},Age:{{ user.age }}</h3>
        <h3>{{ ls[0] }}---{{ ls[1] }}---{{ ls[2] }}</h3>
    </div>

    <!-- introduce vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        const app = new Vue({
            el:"#app",//element is used to define a scope for vue instances
            data:{
                msg:"Handsome dragon I love you!",
                user:{name:"Little black dragon",age:20},
                ls:["Xiaomei","Xiaohua","Xiao Shan"]
            },
        });
    </script>
</body>
</html>
# summary
1.vue Instance el attribute:representative vue The scope of action can be used anywhere under the scope vue grammar
2.el Property can write any css Selector, but recommended id selector
3.vue Instance data attribute:Used to give vue Instance binds some data. The bound data can be{{Variable name}}In the form of vue Scope of action extraction
4.in use{{}}When obtaining data, you can{{}}Write expressions, operators, call related methods and logical operations in

Template syntax

v-text and v-html

v-text is used to update the original data, or understood as inserting data. Using the form of {}} (interpolation expression) will cause interpolation flicker in the case of poor network, but it will not affect it in general

v-text parses the html tag contained in the data and then renders it inside the tag

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>first vue program</title>
</head>
<body>
    <div id="app">
        <div v-text="msg"></div>
        <div v-html="msg"></div>
    </div>

    <!-- introduce vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        const app = new Vue({
            el:"#app",
            data:{
                msg:"<a href=''>Handsome dragon I love you</a>"
            }
        });
    </script>
</body>
</html>

v-on binding function

More advanced ones include setting shape participation arguments and setting event modifiers, which are triggered only when certain conditions are met, such as @ keyup Enter = "change" it is triggered only when you press enter. keyup is an event

Other event modifiers can be found here https://cn.vuejs.org/v2/api/#v-on

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Binding event</title>
</head>
<body>
    <div id="app">
        <div>Age:{{ age }}</div>
        <input type="button" value="Point my age plus 1" v-on:click="change">
        <input type="button" value="use@Binding event" @click="change">
    </div>

    <!-- introduce vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        const app = new Vue({
            el:"#app",
            data:{
                age:20;
            },
            methods:{//Used to define events in vue
                change:function(){
                    this.age++
                }
            }
        });
    </script>
</body>
</html>
# summary
 Event has three elements: event source:Of the event dmo Element event:A specific action occurs, such as click  monitor:The event handler after a specific action occurs, usually js function
1.vue Binding events are through v-on The instruction is completed in the format:v-on:Event name, for example v-on:click
2.v-on The assignment statement of the event name is the function name triggered by the current event
3.vue The functions of events are uniformly defined in vue Instance methods Attribute
4.stay vue In defined events this Refers to the current vue Instance, you can this obtain vue Instance data and method
5.have access to@Symbol binding events, simplifying v-on
6.methods Functions can be from change:function(){}Simplified as change(){}
7.Defining events can define shape participation arguments

v-show toggle element display status

It will be displayed when the value is true and hidden when the value is false. This value can be the value of data in the vue instance or a logical expression. Eventually, it will be parsed into a Boolean value. Its essence is to switch the display of elements

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Binding event</title>
</head>
<body>
    <div id="app">
        <img src="https://img-blog.csdnimg.cn/20210205151357904.png" v-show="isShow">
        <input type="button" value="Change photo status" @click="change">
    </div>

    <!-- introduce vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        const app = new Vue({
            el:"#app",
            data:{
                isShow:20
            },
            methods:{//Used to define events in vue
                change:function(){
                    this.isShow = !this.isShow;
                }
            }
        });
    </script>
</body>
</html>

v-if switching element display state

The effect is similar to that of v-show. The function is to switch the display status of elements. v-if operates dom elements. If the value is flash, it will be directly removed from the dom tree. If frequent switching, v-show is recommended

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Binding event</title>
</head>
<body>
    <div id="app">
        <img src="https://img-blog.csdnimg.cn/20210205151357904.png" v-if="isShow">
        <input type="button" value="Change photo status" @click="change">
    </div>

    <!-- introduce vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        const app = new Vue({
            el:"#app",
            data:{
                isShow:20
            },
            methods:{//Used to define events in vue
                change:function(){
                    this.isShow = !this.isShow;
                }
            }
        });
    </script>
</body>
</html>

v-bind switch element attribute

The format is v-bind: attribute name = expression, where v-bind is usually omitted (see examples 2 and 3). You can use the object method {active:isActive} to replace the ternary expression

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <style>
        .active {
            border: 1px solid red;
        }
    </style>
</head>
<body>
    <div id="app">
        <img v-bind:src="imgSrc">
        <br>
        <img :src="imgSrc" :title="I love handsome dragons" :class="isActive?'active':''" @click="change">
        <br>
        <img :src="imgSrc" :title="I love handsome dragons" :class="{active:isActive}"  @click="change">
    </div>

    <!-- introduce vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        const app = new Vue({
            el:"#app",
            data:{
                imgSrc:"https://img-blog.csdnimg.cn/20210205151357904.png",
                isActive:true
            },
            methods:{//Used to define events in vue
                change:function(){
                    this.isActive = !this.isActive;
                }
            }
        });
    </script>
</body>
</html>

v-for loop generated list structure

The variables from the loop can be used, and the data of the array is corresponding to the data of the page

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>
    <div id="app">
        <ul>
            <li v-for="(item,index) in objArr" :class="index">full name:{{ item.name }},Age:{{ item.age }}</li>
        </ul>
    </div>

    <!-- introduce vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        const app = new Vue({
            el:"#app",
            data:{
                objArr:[{name:"Zhang San",age:19},{name:"Li Si",age:20}]
            },
        });
    </script>
</body>
</html>

v-mode gets and sets the value of form data (two-way data binding)

Two way binding means that both ends are changed at the same time. Using {}} is a one-way change

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>
    <div id="app">
        <input type="text" v-model="msg" @keyup.enter="test">
        <h2>{{ msg }}</h2>
    </div>

    <!-- introduce vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        const app = new Vue({
            el:"#app",
            data:{
                msg:"I love handsome dragons"
            },
            methods: {
                test(){
                    alert(this.msg)
                }
            },
        });
    </script>
</body>
</html>

Introduction and introduction of axios

Inside is ajax. After encapsulation, the function is single, that is to send requests, so the volume is very small and can be easily combined with other libraries or frameworks

<!-- Official website recommendation -->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<!-- cdn -->
<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>

get request format

axios.get(address?key1=value1&key2=value2).then(
	function(response){
    	//Operation after success
	},
    function(err){
        //Action after failure
    }
)

post request format

axios.get(address,{key1:value1,key2:value2}).then(
	function(response){
    	//Operation after success
	},
    function(err){
        //Action after failure
    }
)

Basic operation of axios

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>axios Basic use</title>
</head>
<body>
    <input type="button" value="get request" class="get">
    <input type="button" value="post request" class="post">
    <!-- Available on the official website axios Online address -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>
        /*
            Interface 1: random joke
            Request address: https://autumnfish.cn/api/joke/list
            Request method: get
            Request parameter: num (number of jokes, number)
            Response content: random jokes
        */
        document.querySelector(".get").onclick = function () {
            axios.get("https://autumnfish.cn/api/joke/list?num=6")
            // axios.get("https://autumnfish.cn/api/joke/list1234?num=6")
            .then(function (response) {
                console.log(response);
              },function(err){
                  console.log(err);
              })
        }
        /*
             Interface 2: user registration
             Request address: https://autumnfish.cn/api/user/reg
             Request method: post
             Request parameters: username (user name, string)
             Response content: Registration success or failure
         */
        document.querySelector(".post").onclick = function () {
            axios.post("https://autumnfish.cn/api/user/reg",{username:" salt baked broccoli "})
            .then(function(response){
                console.log(response);
                console.log(this.skill);
            },function (err) {
                console.log(err);
              })
          }
    </script>
</body>
</html>

Combination of axios and vue

It should be noted that a copy of this should be created before sending the request, which is usually called_ This, and then use the copy to operate the vue element, otherwise the vue will be destroyed with the end of the request

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>axios+vue</title>
</head>

<body>
    <div id="app">
        <input type="button" value="Get jokes" @click="getJoke">
        <p> {{ joke }}</p>
    </div>
    <!-- Available on the official website axios Online address -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <!-- Development environment version with helpful command line warnings -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        /*
            Interface: randomly get a joke
            Request address: https://autumnfish.cn/api/joke
            Request method: get
            Request parameters: None
            Response content: random jokes
        */
        var app = new Vue({
            el:"#app",
            data:{
                joke:"A funny joke"
            },
            methods: {
                getJoke:function(){
                    // console.log(this.joke);
                    var _this = this;
                    axios.get("https://autumnfish.cn/api/joke").then(function(response){
                        // console.log(response)
                        console.log(response.data);
                        // console.log(this.joke);
                        _this.joke = response.data;
                    },function (err) {  })
                }
            },
        })
    </script>
</body>
</html>

Life cycle hook

A vue instance is mainly divided into three stages

  • establish
  • function
  • Destroy
functioneffect
beforeCreate()The vue instance is executed before initialization and can act as this pointer
created()After the vue instance is initialized, it is executed to initialize the methods in data and methods
beforeMount()Compile the specified el area template, and data rendering has not been performed at this time
mounted()Render data and update interface
beforeUpdate()Update data in vue
updated()Update the data of the page
beforeDestroy()The methods in data and methods have not been destroyed
destroy()The methods in data and methods are destroyed
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>first vue program</title>
</head>
<body>
    <div id="app">
        <h3 id="title">{{ msg }}</h3>
    </div>

    <!-- introduce vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        const app = new Vue({
            el:"#app",//element is used to define a scope for vue instances
            data:{
                msg:"Handsome dragon I love you!",
            },
            beforeCreate() {//The vue instance is executed before initialization. You can use this pointer
                console.log(this.msg);
            },
            created() {//Execute after vue instance initialization
                console.log(this.msg);
            },
        });
    </script>
</body>
</html>

Keywords: Javascript Vue

Added by Jeroen Oosterlaar on Sat, 29 Jan 2022 08:03:05 +0200