[Vue] dark horse Vue quick start notes

[Vue] dark horse Vue quick start notes

brief introduction

Vue (pronunciation / vju) ː/, Similar to view), it is a set of progressive [JavaScript] framework for building [user interface]. 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 combined with modern tool chains and various support [class libraries], Vue can also provide drivers for complex single page applications ([SPA]).

single page web application (SPA) is an application with only one Web page. It is a Web application that loads a single HTML page and dynamically updates the page when the user interacts with the application.

1. JavaScript framework

2. Simplify Dom operation

3. Responsive data driven

Characteristics and advantages of Vue

vue has two characteristics: responsive programming and componentization.

Advantages of vue

Lightweight framework, easy to learn, two-way data binding, componentization, separation of data and structure, virtual DOM and fast running speed.

vue is a single page application, which makes the page refresh locally without requesting all data and dom every time you jump to the page, which greatly speeds up the access speed and improves the user experience. And his third-party ui libraries save a lot of development time.

lightweight framework 
Only focus on layers,Is a collection of views that build data,The size is only dozens kb
Vue.js Through concise API Provide efficient data binding and flexible component system

Easy to learn
 Chinese development,Chinese documents,There is no language barrier,Easy to understand and learn

Bidirectional data binding
 This is called responsive data binding. The response here is not@media Responsive layout in media query, but refers to vue.js It will automatically respond synchronously to the changes of some data in the page.
in other words, vue.js It will automatically respond to data changes, and modify all bound data and view contents according to the binding relationship written in advance by the user in the code. And this binding relationship is based on input Tagged v-model Attribute, so you may see some people call it roughly elsewhere vue.js Template engine for declarative rendering.
This is vue.js The greatest advantage, through MVVM The idea is to realize the two-way binding of data, so that developers don't have to operate anymore dom Object, have more time to think about business logic.

Componentization
 In front-end applications, can we package modules like programming? This introduces the idea of component development.
Vue.js Through components, various modules in a single page application are divided into a single component( component)In, we just need to write all kinds of component labels (pit filling) in the parent application, and write the parameters to be passed into the component in the component label (just like passing parameters to the function, this parameter is called the component attribute), and then write the implementation (pit filling) of all kinds of components respectively, and then the whole application is finished.

view,data,Structural separation
 Make data changes easier,No modification of logic code is required,You only need to manipulate the data to complete the relevant operations

fictitious DOM
 Now the Internet speed is getting faster and faster. Many people have dozens or even hundreds of them M Optical fiber, mobile phone is also 4 G Started, according to reason, a web page is only a few hundred K,Moreover, the browser itself will cache many resource files, so dozens M Why does it feel slow to open a page that has been opened before and has a cache? This is because the browser itself handles DOM There are also performance bottlenecks, especially in traditional development JQuery Or native JavaScript DOM Operation function pair DOM During frequent operations, the browser constantly renders new images DOM The tree makes the page look very Caton.
and Virtual DOM Is virtual DOM In short, he is a kind of English that can be passed in advance JavaScript Carry out various calculations and put the final DOM The operation is calculated and optimized due to this DOM Operation is a preprocessing operation, and there is no real operation DOM,So it's called virtual DOM. Finally, after the calculation, the DOM Operation submission, will DOM Operational changes are reflected in DOM On the tree.

Faster operation
 Image comparison and react for,They are also virtual operations dom,In terms of performance,vue There are great advantages

Disadvantages of vue

1. Vue does not lack introductory tutorials, but it lacks high-level tutorials and documents. There are also books.

2. VUE does not support IE8

3. The ecological environment is worse than angular and react

Anglar: modern Web Development platform
React: For building user interfaces JavaScript library

4. Small community

First Vue program

  • Import a development version of Vue js

    Create a html file , and then introduce Vue as follows:

    <!-- Development environment version with helpful command line warnings -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    
  • Create a Vue instance object and set the el attribute and data attribute

    • el: mount point

    [scope of Vue instance]

    Vue manages the elements hit by the el option and their internal descendants

    [whether other selectors can be used]

    Other selectors can be used, but ID selectors are recommended

    [whether other dom elements can be set]

    You can use other double tags, not HTML and BODY

    • Data: data object

      All the data that Vue instances need to use exists in data

      Complex types of data can be written in data

      When rendering complex types of data, just follow the syntax of js

    • methods: methods

  • Use concise template syntax to render data to the page

<!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>Vue Test 001</title>
</head>
<body>
    {{ message }}
    <div id="app" class="app">
            {{ message }} <!-- "{" Interpolation expression-->
            <span> {{ message }} </span>
            <h2> {{ school.name }} {{ school.mobile }} </h2>
            <ul>
                <li>{{ campus[0] }}</li>
                <li>{{ campus[1] }}</li>
            </ul>
    </div>
    <!-- Development environment version with helpful command line warnings -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
    <script>
        var app = new Vue({
         //   El: '#app', / / in css selector '#' is an id selector
         //[it is actually developed and used to avoid unclear semantics, and can only support double labels]
         //Do not mount vue on < body > / < HTML >, but on other tags, such as div
         //   el:".app", / / in css selector "." Is a class selector
            el:"div", //Label selector in css selector
            data:{
                message:"Hello!", //Basic type string message
                school:{            //Object, take the object and use "."
                    name:"CYQAQ",
                    mobile:"55555"
                },
                campus:["Beijing","Shanghai","Guangzhou","Shenzhen"] //Array, get the index of the elements in the array
            }
        })
    </script>
</body>
</html>

Vue local application

  • Achieve common web page effects through Vue
  • Learn Vue instructions and consolidate knowledge points with cases
  • The Vue instruction refers to a special set of syntax that begins with * * v - *

1. Content binding, event binding

v-text

Set the text value of the label / element (textContent)

  • The default writing method will replace all contents, and the specified contents can be replaced by the difference expression {}}

  • Write expression is supported internally

    <!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>Vue Test 002</title>
    </head>
    <body>
        <div id="app">
            <h2 v-text="message+'!'">Shenzhen</h2> <!--Pay attention to string splicing“ ' Use of-->
            <h2 v-text="info+'!'">Shenzhen</h2> <!--vue The command will not be displayed-->
            <h2>Shenzhen{{ message + "!"}}</h2> <!--To partially replace, use{{}}-->
            <h2 v-text="content"></h2> <!--v-text Will not resolve html-->
        </div>
        <!-- Development environment version with helpful command line warnings -->
        <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
        <script>
            var app = new Vue({
                el:"#app", 
                data:{
                    message:"CYQAQ",
                    info:"dididi",
                    content:"<a href='#'>CYQAQ</a>"
                }
            })
        </script>  
        </body>
    </html>
    

v-html

Set innerHTML for tag / element

  • html structures in the content will be parsed into tags

  • The v-text instruction will only parse into text regardless of its content

  • v-text is used for parsing text, and v-html is used for parsing HTML structure

    <!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>Vue Test 003</title>
    </head>
    
    <body>
        <div id="app">
           <p v-html="content"></p> <!--v-html Can resolve html-->
        </div>
        <!-- Development environment version with helpful command line warnings -->
        <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
        <script>
            var app = new Vue({
                el:"#app", 
                data:{
                    //content:"CYQAQ"
                    content:"<a href='https://cn.vuejs.org/v2/guide/'>Vue.js</a>"
                }
            })
        </script>
    </body>
    </html>
    

v-on Foundation

Binding events for elements

  • The event name does not need to be written on

  • Instructions can be abbreviated as@

  • The bound method is defined in the methods property

  • Method can access the data defined in data through the this keyword

    <!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>Vue Test 003</title>
    </head>
    
    <body>
        <div id="app">
           <!--<input type="button" value="Event binding" v-on:Event name="method">-->
           <input type="button" value="Event binding" v-on:click="doIt"><!--Click event-->
           <input type="button" value="Event binding" v-on:monseenter="doIt"><!--Mouse in event-->
           <input type="button" value="Event binding" v-on:dblclick="doIt"><!--Double click the event-->
           <input type="button" value="Event binding" @dblclick="doIt">
           <h2 @click="changeFood">{{ food }}</h2>
        </div>
        <!-- Development environment version with helpful command line warnings -->
        <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
        <script>
            var app = new Vue({
                el:"#app", 
                data:{
                    food:"Scrambled eggs"
                },
                methods:{
                    doIt:function(){//logic
                        alert("do IT");
                    },
                    changeFood:function(){
                        //console.log(this.food);   You need to use this to get the data in the method
                        this.food+="yummy!"
                    }
                },
            })
        </script>
    </body>
    </html>
    
Counter application:
<!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>Vue_Counter</title>
    <link rel="stylesheet" href="index.css"/>
</head>
<body>
    <div id="app" >
        <div class="input-num">
            <button @click="sub">
                -
            </button>
            <span>{{ num }}</span>
            <button @click="add">
                +
            </button>
        </div>
    </div>
    <!-- Development environment version with helpful command line warnings -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
    <script>
        var app = new Vue({
            el:"#app", 
            data:{
                num:1
            },
            methods:{
                add:function(){
                   // console.log('add')
                   if(this.num < 10){
                       this.num++;
                   } else {
                       alert('Don't order xd!No!');
                   }
                },
                sub:function(){
                    //  console.log('sub')
                    if(this.num > 0){
                        this.num--;
                    } else {
                        alert('Don't order xd!No!');
                    }
            
                }
            }
        })
    </script>
</body>
</html>

[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-KLU6EY3H-1640933793544)(F:\Qianduanjichu\notes\counter.png)]

2. Display switching and attribute binding

v-show

Switch the display and hiding of elements (advertisement / mask layer) according to the authenticity of the expression

  • The essence is to modify the display of elements to realize display and hiding

  • The contents after the instruction will eventually be resolved to Boolean values

  • Elements with a value of true are displayed and elements with a value of false are hidden

    <!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>Vue_v-show</title>
    </head>
    <body>
        <div id="app">
            <input type="button" value="Toggle display state" @click="changeIsShow"><br/>
           <!--<img src="monkey.gif" v-show="true">-->
            <img src="monkey.gif" v-show="isShow" alt="">
            <input type="button" value="age" @click="addAge"><br/>
            <img src="monkey.gif" v-show="age >= 18">
        </div>
        <!-- Development environment version with helpful command line warnings -->
        <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
        <script>
            var app = new Vue({
                el:"#app", 
                data:{
                    isShow:false,
                    age:15
                },
                methods:{
                    changeIsShow:function(){
                        this.isShow = !this.isShow;
                    },
                    addAge:function(){
                        this.age++;
                    }
                }
            })
        </script>
    </body>
    </html>
    
    

v-if

Switch the display and hiding of elements according to the true or false expression (essentially manipulate dom elements)

  • Manipulating the dom tree consumes a lot of performance. v-show is used for frequently switched elements, and v-if is used on the contrary

  • When the expression value is true, the element exists in the dom tree and is false. It is removed from the dom tree

    <!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>Vue_v-if</title>
    </head>
    <body>
        <div id="app">
          <!-- <p v-if="true">I am p label</p>--> 
          <input type="button" value="Toggle display state" @click="toggleIsShow" alt="">
            <p v-if="isShow">ah</p>
            <p v-show="isShow">RUA!</p>
            <h2 v-if="temperature >= 35">heat death!!!</h2>
        </div>
        <!-- Development environment version with helpful command line warnings -->
        <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
        <script>
            var app = new Vue({
                el:"#app", 
                data:{
                    isShow:false,
                    temperature:40
                },
                methods:{
                    toggleIsShow:function(){
                        this.isShow = !this.isShow;
                    }
                }
            })
        </script>
    </body>
    </html>
    
    

v-bind

**Bind attributes * * (such as src, title, class) to elements

  • The complete writing method is v-bind: attribute name = expression

  • For short, v-bind can be omitted and only the attribute name is reserved

  • You need to dynamically add or delete class es. It is recommended to use objects

     <!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>Vue_v-bind</title>
        <style>
            .active{
                border: 1px solid red;
            }
        </style>
    </head>
    <body>
        <div id="app">
          <!-- <img src="monkey.gif">-->
          <img v-bind:src="imgSrc" alt="">
          <br> 
          <!--The next method is more commonly used-->
          <img :src="imgSrc" alt="" :title="imgTitle+'!!!'" :class="isActive?'active':''"
           @click="toggleActive">
           <br> 
          <!--There are two ways:
          Ternary expression:<img v-bind:class="isActive?'active':''">
          Object form:<img v-bind:class="{active:isActive}">-->
        </div>
        <!-- Development environment version with helpful command line warnings -->
        <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
        <script>
            var app = new Vue({
                el:"#app", 
                data:{
                   imgSrc:"monkey.gif",
                   imgTitle:"Cheng xuape",
                   isActive:false
                },
                methods:{
                    toggleActive:function(){
                        this.isActive = !this.isActive;
                    }
                }
            })
        </script>
    </body>
    </html>
    
    
Picture switching case:
  • The list data is saved using an array
  • The v-bind instruction can set element attributes, such as src
  • Both v-show and v-if can switch the display state of elements. V-show is used for frequent switching
<!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>Vue_Picture switching</title>
    <link rel="stylesheet" href="index.css">
</head>

<body>
    <div id="mask">
        <div class="center">
            <h2 class="title">
                <img src="logo.png" alt="">This is an advertisement
            </h2>
            <!--picture-->
            <img :src="imgArr[index]" alt="" />
            <!--left arrow-->
            <a href="javascript:void(0)" v-show="index != 0" @click="prev" class="left">
                <img src="prev.png" alt="" />
            </a>
            <!--Right arrow-->
            <a href="javascript:void(0)" v-show="index < imgArr.length - 1" @click="next" class="right">
                <img src="next.png" alt="" />
            </a>
        </div>
    </div>
    <!-- Development environment version with helpful command line warnings -->
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
    <script>
        var app = new Vue({
            el:"#mask", 
            data:{
                imgArr:[
                    "00.jpg",
                    "01.jpg",
                    "02.jpg",
                    "03.jpg",
                    "04.jpg",
                    "05.jpg",
                    "06.jpg",
                    "07.jpg",
                    "08.jpg",
                    "09.jpg",
                    "10.jpg",
                ],
                index:0
            },
            methods:{
                prev:function(){
                    this.index--;
                },
                next:function(){
                    this.index++;
                }
            }
        })
    </script>
</body>
</html>

3. List loop, form element binding

v-for

Generate list structure from data

  • Arrays are often used in conjunction with v-for

  • The syntax is * * (item, index) in data * * / / item represents each item and index represents index

  • item and index can be used in conjunction with other instructions

  • The update of array length will be synchronized to the page, which is responsive

    <!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>Vue_v-for</title>
    </head>
    <body>
        <div id="app">
            <input type="button" value="Add data" @click="add">
            <input type="button" value="Remove data" @click="remove">
            <ul>
                <li v-for="(item,index) in arr" :title="item">
                  Serial number:  {{ index }}    {{ item }}
                </li>
                <li v-for="(item,index) in objArr">
                    {{ item.name }}
                </li>
            </ul>
            <h2 v-for="item in vegetables" v-bind:title="item.name">
                {{ item.name }}
            </h2>
        </div>
        <!-- Development environment version with helpful command line warnings -->
        <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
        <script>
            var app = new Vue({
                el:"#app", 
                data:{
                   arr:["Beijing","Shanghai","Guangzhou","Shenzhen"],
                   objArr:[
                       { name:"jack" },
                       { name:"rose" }
                   ],
                    vegetables:[
                        {name:"Fried egg with Broccoli"},
                        {name:"Fried broccoli with egg"}
                    ]
                },
                methods:{
                    add:function(){
                        this.vegetables.push({name:"Scrambled egg with cauliflower"})
                    },
                    remove:function(){
                        this.vegetables.shift();  //The shift() method removes the first element of the array from it and returns the value of the first element.
                    }
                }
            })
        </script>
    </body>
    </html>
    
    

v-on supplement

Pass custom parameters, event modifiers

  • Event bound methods are written in the form of function calls, and user-defined parameters can be passed in

  • When defining a method, you need to define formal parameters to receive the incoming arguments

  • Follow the events Modifiers can limit events

  • . enter can limit the triggered key to enter

  • There are many kinds of event modifiers:

    • . stop - call event stopPropagation().
    • . prevent - call event preventDefault().
    • . capture - use capture mode when adding event listeners.
    • . self - the callback is triggered only when the event is triggered from the listener bound element itself.
    • . {keyCode | keyAlias} - the callback is triggered only when the event is triggered from a specific key.
    • . native - listens for native events of the component root element.
    • . once - only one callback is triggered.
    • . left - (2.2.0) triggered only when the left mouse button is clicked.
    • . right - (2.2.0) triggered only when the right mouse button is clicked.
    • . middle - (2.2.0) triggered only when the middle mouse button is clicked.
    • . passive - (2.3.0) add listener in {passive: true} mode
  • <!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>Vue_v-for</title>
    </head>
    <body>
        <div id="app">
            <input type="button" value="Dot me" @click="doIt(666,'Lao')">
            <input type="text" @keyup.enter="sayHi">
        </div>
        <!-- Development environment version with helpful command line warnings -->
        <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
        <script>
            var app = new Vue({
                el:"#app", 
                methods:{
                    doIt:function(p1,p2){
                        console.log("do it");
                        console.log(p1);
                        console.log(p2);
                    },
                    sayHi:function(){
                        alert("EAT");
                    }
                }
            })
        </script>
    </body>
    </html>
    
    

v-model

Set value of form element (bidirectional data binding) [dynamic]

  • The function of v-model instruction is to set and obtain the value of form elements conveniently

  • The bound data is associated with the form element value

  • Bound data ⬅➡ Value of form element [bidirectional binding]

    <!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>Vue_v-for</title>
    </head>
    <body>
        <div id="app">
            <input type="button" value="modify message" @click="setM">
            <input type="text" v-model="message" @keyup.enter="getM">
            <h2>{{ message }}</h2>
        </div>
        <!-- Development environment version with helpful command line warnings -->
        <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
        <script>
            var app = new Vue({
                el:"#app", 
                data:{
                    message:"Wonderful"
                },
                methods:{
                    getM:function(){
                        alert(this.message);
                    },
                    setM:function(){
                        this.message = "Cool";
                    }
                }
            })
        </script>
    </body>
    </html>
    
    
Notepad case:
  • newly added

    • Generate list structure (v-for array)
    • Get user input (v-model bidirectional data binding can quickly set and get the value of form elements)
    • Press enter to add data (the event binding v-on can also pass the user-defined parameter enter limit. Enter to add data)
    • Quick positioning by reviewing elements
  • delete

    • Click to delete the specified content (v-on: event binding splice: method of array deletion instruction index: index)

    • Data changes and data binding elements change synchronously

    • Custom parameters for events

    • The splice() method adds / removes items to / from the array, and then returns the deleted items.

      [deleting the corresponding element according to the index will directly modify the array.]

      arrayObject.splice(index,howmany,item1,.....,itemX)
      index	Required. Integer, specifying addition/Delete the position of the item. Use a negative number to specify the position from the end of the array.
      howmany	Required. Number of items to delete. If set to 0, the item is not deleted.
      item1, ..., itemX	Optional. Adds a new item to the array.
      
      
  • Statistics

    • Number of statistical information (essentially the length of the array v-text length)
    • Data based development
    • The purpose of the v-text instruction is to set the text
  • empty

    • Click to clear all information (v-on clear array)
    • Based on the data development method, the page is the display of data. Empty the list, directly empty the array and empty the array.
  • hide

    • Hide elements when there is no data (v-show v-if array is not empty)

      <!DOCTYPE html>
      <html lang="en">
      <head>
          <title>Vue_notepad</title>
          <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
          <meta name="robots" content="noindex,nofollow"/>
          <meta name="googlebot" content="noindex,nofollow"/>
          <meta name="viewport" content="width=device-width,initial-scale=1"/>
          <link rel="stylesheet" type="text/css" href="index.css"/>
      </head>
      <body>
          <!--Main area-->
          <section id="todoapp">
              <!--Input box-->
              <header class="header">
                  <h1>Notepad</h1>
                  <input v-model="inputValue" @keyup.enter="add" autofocus="autofocus" autocomplete="off" 
                  placeholder="Please enter a task" class="new-todo"/>
              </header>
              <!--List area-->
              <section class="main">
                  <ul class="todo-list">
                      <li class="todo" v-for="(item,index) in list">
                          <div class="view">
                              <span class="index">{{ index+1 }}.</span>
                              <label>{{ item }}</label>
                              <button class="destroy" @click="remove(index)"></button>
                          </div>
                      </li>
                  </ul>
              </section>
              <!--Statistics and emptying-->
              <footer class="footer" v-show="list.length!=0">
                  <span class="todo-count" v-if="list.length!=0">
                      <strong>{{ list.length }}</strong>
                      items left
                  </span>
                  <button class="clear-completed" @click="clear" v-show="list.length!=0">
                      Clear
                  </button>
              </footer>
          </section>
          <footer class="info">
              <p>
                  <a href="https://www.baidu.com/"><img src="black.png" alt="" ></a>
              </p>
          </footer>
          <!-- Development environment version with helpful command line warnings -->
          <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
          <script>
              var app = new Vue({
                  el:"#todoapp", 
                  data:{
                      list:["IT","EAT","SLEEP"],
                      inputValue:"GOOD GOOD STUDY,DAY DAY UP"
                  },
                  methods:{
                      add:function(){
                          this.list.push(this.inputValue);
                      },
                      remove:function(index){
                          console.log("delete");
                          console.log(index);
                          this.list.splice(index,1);
                      },
                      clear:function(){
                          this.list = [];
                      }
                  }
              })
          </script>
      </body>
      </html>
      
      

Vue network application

Development and application of vue combined with network data

axios

Axios is a promise based that can be used in browsers and nodes Asynchronous communication framework in JS; [network request library]

The main function is to realize AJAX asynchronous communication.

(Axios is an HTTP client based on Promise for browsers and nodejs. The simple understanding is the encapsulation of ajax.)

Because the boundary of vue is very clear, it is to deal with DOM, so it does not have communication function. At this time, it is necessary to use the axios communication framework to interact with the server.

It has the following characteristics:

  • Create XMLHttpRequest from browser
  • From node JS issue http request
  • Promise API supported
  • Intercept requests and responses
  • Transform request and response data
  • Cancel request
  • Automatically convert JSON data
  • Client support prevents CSRF/XSRF

install

Install using npm:

$ npm install axios

Using bower:

$ bower install axios

Or use cdn directly:

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

Use examples

  • axios. Get (address? Key = value & key2 = Value2) then(function(respones)){},function(err){})
  • axios. Post (address, {key: value, key2: Value2}) then(function(response){},function(err){})
  • axios must be imported before it can be used
  • Use the get or post method to send the corresponding request
  • The callback function in the then method is triggered when the request succeeds or fails
  • The response content or error information can be obtained through the formal parameters of the callback function
  • Document transfer: https://github.com/axios/axios

Some small interfaces

  • https://autumnfish.cn/api/joke/list

    Get request to get the parameter, num

  • https://autumnfish.cn/api/user/reg

    post request to obtain registration success or failure, parameter username

  • http://wthrcdn.etouch.cn/weather-mini

    get request to obtain weather information, parameter city

    <!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 test</title>
    </head>
    <body> 
        <input type="button" value="get request" class="get">
        <input type="button" value="post request"class="post">
        <!--axios Online address-->
        <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
        <script>
            //Interface 1
            document.querySelector(".get").onclick = function () {
                axios.get("https://autumnfish.cn/api/joke/list?num=3")
                .then(function(response){
                    console.log(response);
                },function(err){
                    console.log(err);
                })
            }
            //Interface 2
            document.querySelector(".post").onclick = function () {
                axios.post("https://autumnfish.cn/api/user/reg",
                {username:"jack1111111"} )
                .then(function(response){
                    console.log(response);
                },function(err){
                    console.log(err);
                })
            }
          
        </script>
    </body>
    </html>
    
    

axios+vue

  • this in the axios callback function has been changed and the data in data cannot be accessed

  • Save this and directly use the saved this in the callback function

  • The biggest difference between and local applications is the change of data source

    <!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 test</title>
    </head>
    <body> 
        <div id="app">
            <input type="button" value="Get jokes" @click="getJoke">
            <p>{{ joke }}</p>
        </div>
        <!--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>
            var app = new Vue({
                el:"#app",
                data:{
                    joke:"A funny joke"
                },
                methods:{
                    getJoke:function(){
                        //console.log(this.joke);
                        var that = this;
                        axios.get("https://autumnfish.cn/api/joke")
                        .then(function(response){
                            console.log(response.data);
                            //console.log(this.joke);
                            that.joke = response.data;
                        },function(err){
    
                        })
                    }
                }
            })
        </script>
    </body>
    </html>
    
    
Weather forecast case:
  • Press enter to query the weather
    • Press enter (v-on. Enter)
    • Query data (axios interface v-model)
    • Render data (v-for array that)
    • The logic code of the application is suggested to be separated from the page and written in a separate js file
    • The this point in the axios callback function has changed, so an additional copy needs to be saved
    • When the data returned by the server is complex, you need to pay attention to the hierarchy when obtaining it
  • Click to query weather
    • Click city (v-on custom parameter)
    • Query data (this. Method ())
    • Render data
    • Custom parameters can make the code more reusable
    • Within the method defined in methods, you can point out other methods through the keyword this
<!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>God knows</title>
  <link rel="stylesheet" href="css/reset.css" />
  <link rel="stylesheet" href="css/index.css" />
</head>
<body> 
    <div class="wrap" id="app">
        <div class="search_form">
            <div class="logo">
                <img src="img/logo.png" alt="logo" />
            </div>
            <div class="form_group">
                <input type="text" v-model="city" @keyup.enter="searchWeather" class="input_txt" placeholder="Please enter the weather to query" />
                <button class="input_sub" @click="searchWeather">
                    Search
                </button>
            </div>
            <div class="hotkey">
                <a href="javascript:;" @click="changeCity('Beijing')">Beijing</a>
                <a href="javascript:;" @click="changeCity('Shanghai')">Shanghai</a>
                <a href="javascript:;" @click="changeCity('Guangzhou')">Guangzhou</a>
                <a href="javascript:;" @click="changeCity('Shenzhen')">Shenzhen</a>
            </div>
        </div>
        <ul class="weather_list">
            <li v-for="item in weatherList">
                <div class="info_type">
                    <span class="iconfont">{{ item.type }}</span></div>
                <div class="info_temp">
                  <b>{{ item.low }}</b>
                  ~
                  <b>{{ item.high }}</b>
                </div>
                <div class="info_date"><span>{{ item.date }}</span></div>
            </li>
        </ul>
        </div>
        <!-- Development environment version with helpful command line warnings -->
        <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
        <!-- Available on the official website axios Online address -->
        <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
        <!-- own js -->
        <script src="./js/main.js"></script>
</body>
</html>

var app = new Vue({
     el:"#app",
     data:{
         city:"",
         weatherList:[]
     },
     methods: {
         searchWeather:function(){
            //console.log('weather query ');
            //console.log(this.city);
            // Call interface
            // This will change in the callback function. Save this in advance
            var that = this;
            axios.get('http://wthrcdn.etouch.cn/weather_mini?city='+this.city)
            .then(function(response){
                //console.log(response);
                console.log(response.data.data.forecast);
                that.weatherList = response.data.data.forecast;
            })
            .catch(function(err){})
         },
         changeCity:function(city){
            this.city = city;
            this.searchWeather();
         }
     },
 })

Vue integrated application

music player

Song search

  • Press enter (v-on. Enter)

  • Query data (axios interface v-model)

  • Render data (v-for array that)

  • Song search interface: https://autumnfish.cn/serch

    Use get to request song search results, and the parameter keywords (query keywords)

  • When the data returned by the server is complex, you need to pay attention to the hierarchy when obtaining it

  • Quickly locate the elements to be manipulated by reviewing the elements

Song playing

  • Click play (v-on custom parameters)

  • Song address acquisition interface (song id)

  • Song address setting (v-bind)

  • Song URL acquisition interface: request address: https://autumnfish.cn/song/url

    Use get to request song url address, parameter: ID (song id)

  • Song id depends on the results of song search, and it also needs to pay attention to unused data

Song cover

  • Click play (add logic)

  • Song cover acquisition interface (song id)

  • Song cover settings (v-bind)

  • Song details: request address: https://autumnfish.cn/song/detail

    Use get to request song details (including cover information), parameter: IDS (song id)

  • Manipulating attributes through v-bind in vue

  • Data that cannot be obtained locally will basically have corresponding interfaces

Song review

  • Click play (add logic)

  • Song comment acquisition interface (song id)

  • Song review rendering (v-for)

  • Hot comment request address: https://autumnfish.cn/comment/hot?type=0

    Use get to request popular comments of songs. Parameters: id (song id, type in address is fixed to 0)

  • Generating lists from v-for in vue

Play animation

  • Monitor music play (v-on play)
  • Listen to music pause (v-on pause)
  • Manipulation class name (v-bind object)
  • The play event of audio tag will be triggered when playing
  • The pause event of audio tag will be triggered when pausing
  • Set the class name through the object. The effectiveness of the class name depends on whether the following values are true or false

mv Play

  • mv chart display (v-if)

  • mv address acquisition (interface mvid)

  • Mask layer (v-show v-on)

  • mv address setting (v-bind)

  • MV address acquisition: request address: https://autumnfish.cn/mv/url

    Use get to request the address of mv. Parameter: id(mvid, 0 means no mv)

  • Different interfaces require different data, and the document needs to be read carefully

  • After the page structure is complex, quickly locate relevant elements by reviewing elements

  • All responsive data needs to be defined in data

/*
  1:Song search interface
    Request address: https://autumnfish.cn/search
    Request method: get
    Request parameter: Keywords
    Response content: song search results
  2:Song url acquisition interface
    Request address: https://autumnfish.cn/song/url
    Request method: get
    Request parameter: ID (song id)
    Response content: Song url address
  3.Get song details
    Request address: https://autumnfish.cn/song/detail
    Request method: get
    Request parameter: IDS (song id)
    Response content: Song details (including cover information)
  4.Get hot comments
    Request address: https://autumnfish.cn/comment/hot?type=0
    Request method: get
    Request parameter: id (song id, type in address is fixed as 0)
    Response content: popular reviews of songs
  5.mv Address acquisition
    Request address: https://autumnfish.cn/mv/url
    Request method: get
    Request parameter: id(mvid, 0 means no mv)
    Response content: mv address
*/

var app = new Vue({
  el: "#player",
  data:{
    //Query keyword
    query:"",
    //Song array
    musicList:[],
    //Song address
    musicUrl:"",
    //Song cover
    musicCover:"",
    //Song review
    hotComments:[],
    //Animation playback status
    isPlaying:false,
    //Display state of mask layer
    isShow:false,
    //mv address
    mvUrl:""
  },
  methods:{
    //Song search
    searchMusic:function(){
      var that = this;
      axios.get("https://autumnfish.cn/search?keywords="+this.query)
      .then(function(response){
        //console.log(response);
        that.musicList = response.data.result.songs;
        console.log(response.data.result.songs);
      },function(err){})
    },
    //Song playing
    playMusic:function(musicId){
      // console.log(musicId);
      var that = this;
      axios.get("https://autumnfish.cn/song/url?id="+musicId)
      .then(function(response){
       // console.log(response);
       // console.log(response.data.data[0].url);
       that.musicUrl = response.data.data[0].url;
      },function(err){})
      //Get song details
      axios.get("https://autumnfish.cn/song/detail?ids="+musicId)
      .then(function(response){
        //console.log(response);
        console.log(response.data.songs[0].al.picUrl);
        that.musicCover = response.data.songs[0].al.picUrl;
      },function(err){})
      //Get song Reviews
      axios.get("https://autumnfish.cn/comment/hot?type=0&id="+musicId)
      .then(function(response){
        //console.log(response);
       console.log(response.data.hotComments);
       that.hotComments = response.data.hotComments;
      },function(err){})
    },
    //play
    play:function(){
    //  console.log("play");
      var that = this;
      that.isPlaying = true;
    },
    //suspend
    pause:function(){
     // console.log("pause");
      var that = this;
      this.isPlaying = false;
    },
    //Play mv
    playMV:function(mvid){
      var that = this;
      axios.get("https://autumnfish.cn/mv/url?id="+mvid)
      .then(function(response){
        //console.log(response);
        console.log(response.data.data.url);
        that.isShow = true;
        that.mvUrl = response.data.data.url;
      },function(err){})
    },
    //hide
    hide:function(){
      this.isShow = false;
    }
    
  }
  
});


<!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>Pleasant listening</title>
        <!--style-->
        <link rel="shortcut icon" href="#"/>
        <link rel="stylesheet" href="./css/index.css">
    </head>
    <body>
        <div class="wrap">
            <!--Player body area-->
            <div class="play_wrap" id="player">
                <div class="search_bar">
                    <img src="images/player_title.png" alt=""/>
                    <!--Search for songs-->
                    <input type="text" autocomplete="off" v-model="query" @keyup.enter="searchMusic" />
                </div>
                <div class="center_con">
                    <!--Search song list-->
                    <div class="song_wrapper">
                        <ul class="song_list">
                            <li  v-for="item in musicList">
                                <a href="javascript:;" @click="playMusic(item.id)"></a> 
                                <b>{{ item.name }}</b> 
                                <span v-if="item.mvid!=0" @click="playMV(item.mvid)"><i></i></span>
                            </li>
                        </ul>
                        <img src="images/line.png" class="switch_btn" alt="">
                    </div>
                    <!--Song information container-->
                    <div class="player_con" :class="{playing:isPlaying}">
                        <img src="images/player_bar.png" class="play_bar"/>
                        <!--Black glue-->
                        <img src="images/disc.png" class="disc autoRotate"/>
                        <img :src="musicCover" class="cover autoRotate" />
                    </div>
                    <!--Comment container-->
                    <div class="comment_wrapper">
                        <h5 class='title'>Popular message</h5>
                        <div class='comment_list'>
                        <dl v-for="item in hotComments">
                            <dt>
                                <img :src="item.user.avatarUrl" alt="">
                            </dt>
                            <dd class="name"> 
                                 {{ item.user.nickname }}
                            </dd>
                            <dd class="detail">
                                {{ item.content }}
                            </dd>
                        </dl>
                        </div>
                        <img src="images/line.png" class="right_line">
                    </div>
                </div>
                <div class="audio_con" > 
                    <!--<audio> Tags define sounds, such as music or other audio streams-->
                    <audio ref='audio' @play="play" @pause="pause" :src="musicUrl" controls autoplay loop class="myaudio"></audio> 
                </div>
                <div class="video_con" v-show="isShow" style="display: none;">
                    <video :src="mvUrl" controls="controls"></video>
                    <div class="mask" @click="hide"></div>
                </div>
               
            </div>
        </div>
        <!--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 src="./js/main.js"></script>
    </body>
</html>

Introduction to UNI-APP

What is UNI-APP

Uni app (uni, read you ni, meaning unified) is a use Vue.js Develop all front end Application framework, developers write a set of code, which can be published to iOS,Android,Web (responsive), and various Applet,Fast application And other platforms.

Uni app is a full-end development framework based on vue syntax

Vue.js is the key to building a Web interface JavaScript Framework is a component system that provides efficient data binding and flexibility through concise API.

What are the works of UNI-APP

CSDN, Kaiyuan China, Kunming Railway +, chongyoubang, jivolunteer, China talent network, Shanghai railway 12306

Community and scale of UNI-APP

  • 3.8 million developers
  • Hundreds of thousands of application cases
  • 850 million mobile end users
  • Thousands of uni app plug-ins
  • 70 + wechat / QQ group

UNI-APP Foundation

Basic knowledge

First experience of uni app

Development mode

  • Use HBuilderX provided by DCloud company for rapid development
  • Use (nodejs based) scaffolding to quickly build and develop
Scaffold construction project

1. Global installation (before that, install nodejs and configure npm)

(ps: domestic is too laggy with npm, and needs to install cnpm image to speed up).

npm install -g @vue/cli
 perhaps cnpm install -g @vue/cli

2. Create project

vue create -p dcloudio/uni-preset-vue my-project

3. Start the project (wechat applet)

npm run dev:mp-weixin

4. Wechat applet developer tool import project

Look at the usefulness of these things before using them:

npm: Nodejs Package manager under.
webpack: Its main purpose is through CommonJS The syntax makes corresponding preparations for all static resources to be published on the browser side, such as resource merging and packaging.
vue-cli: User generated Vue Engineering formwork. (help you get started quickly) vue Project, that is to give you a set vue The structure, including the basic dependency library, only needs npm install Can be installed)
vue.js There is a famous family bucket series, including vue-router,vuex, vue-resource,Plus the build tool vue-cli,Is a complete vue The core composition of the project.

Vue CLI Is based on Vue.js A complete system for rapid development, providing:
-adopt @vue/cli Implement interactive project scaffolding.
-adopt @vue/cli + @vue/cli-service-global Zero configuration prototype development.
-A runtime dependency (@vue/cli-service),This dependency:
.Upgradeable;
.be based on webpack Build with reasonable default configuration;
.It can be configured through the configuration file in the project;
.It can be extended through plug-ins.
-A rich collection of official plug-ins, integrating the best tools in the front-end ecosystem.
-A set of completely graphical creation and management Vue.js User interface for the project.
Vue CLI Committed to Vue Tool base standardization in ecology. It ensures that various building tools can be smoothly connected based on intelligent default configuration, so that you can focus on writing applications without having to spend days struggling with configuration.

UNI-APP project

Project directory

Official documents:

https://uniapp.dcloud.io

I know you're looking for a picture

Technology stack: JavaScript, vue, wechat applet, uni app

Also used: uni UI, uni API, moment JS, gesture encapsulation

Keywords: Javascript Front-end Vue Vue.js

Added by cruzbullit on Wed, 05 Jan 2022 07:47:42 +0200