Vue quick start and basic label use

Start example

1. First introduce the production environment of vue in the html page, and paste the following code in the body tag

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

Insert image description here


2. Let’s do an introductory example, as follows.

Insert image description here


el mount point

The part enclosed in braces will be replaced by the data with the same name in data
Insert image description here

You can also use the class selector, but it is recommended to use the id selector, because the id is unique in actual development
Insert image description here

Vue will manage el optionshit elementand its internalDescendant elements

In fact, it can be matched without the div tag, and it can also be used with the p tag. The premise is that id and el match. But it can only support double tags, such as p, h1, head, etc. (html and body tags are not supported).


data data object

Insert image description here

The object written in data is as follows:
Insert image description here
Insert image description here
to display the data of the object type, you can directly use the defined object name and attribute.
For example
{ { student.name }} { { student.age }}
, in this way, the properties of the object can be directly called and displayed.

For the array declared in data, the usage is as follows:

Insert image description here

How to use:
{ { 数组名[0] }}This is to directly display the first element in the array.


vue basic tags

v-text

Set the text value of the label (textContent)

<h2 v-text="message">hello, world!</h2>

It will replace the content in h2 with the content of the text message.
The example is as follows:
Insert image description here

You can also use interpolation expressions to concatenate strings.

Insert image description here

The results are as follows

Insert image description here


You can also use the following method to perform interpolation expressions

<body>
    <div id="app">
        <h2 v-text="'hello ' + message"></h2>
        <h2>{
    
    {
    
    "hello " + message}}</h2>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
    
    
            el:"#app",
            data:{
    
    
                message:"Chain"
            }
        })
    </script>

Insert image description here
The result is as follows
Insert image description here


  • The function of the v-text instruction is: set the content of the label (textContent)
  • The default wording will replace all the content, use the difference expression {parts} to replace the specified content

v-html

The main function is to render the html code in the tag instead of plain text

<body>
    <div id="app">
        <p v-html="content"></p>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
    
    
            el:"#app",
            data:{
    
          
                content:"<a href='https://www.baidu.com/'>屌毛是你</a>"
            }
        })
    </script>
</body>

The result is as follows: rendered as a link, you can click to jump

Insert image description here

The function of the v-html directive is: if there is an html structure in the innerHTML content of the set element, it will be parsed as a tag. The
v-text directive will only parse it into text no matter what the content is.


v-on

Bind events to elements
Insert image description here

The sample code is as follows:

<body>
    <div id="app">
        <input type="button" value="单击事件" v-on:click="doIt">
        <input type="button" value="单击事件" @click="doIt">
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
    
    
            el:"#app",
            methods:{
    
    
                doIt:function(){
    
    
                    alert("are you 叼毛");
                }
            }
        })
    </script>
</body>

The demonstration results are as follows:
Insert image description here
However, the general use is not so simple, but with various functions and various keywords, as follows

<body>
    <div id="app">

        <input type="button" value="单击事件" v-on:click="doIt">
        <input type="button" value="单击事件" @click="doIt">
        <input type="button" value="双击事件" @dblclick="doIt">

        <h2 @click="changeFood">{
    
    {
    
     food }}</h2>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
    
    
            el:"#app",
            data:{
    
    
                message:"Chain",
                content:"<a href='https://www.baidu.com/'>屌毛是你</a>",
                food:"石头拌稀饭"
            },
            methods:{
    
    
                doIt:function(){
    
    
                    alert("are you 叼毛");
                },
                changeFood:function(){
    
    
                    this.food += "炒鸡好吃!"
                }
            }
        })
    </script>
</body>

Insert image description here
Insert image description here


  • The function of the v-on directive is to bind events to elements
  • The event name does not need to be written on
  • The command can be abbreviated as @
  • The bound method is defined in the methods attribute

Counter example implementation

Probably achieve this effect

Insert image description here
Implement step logic:

1. Define data in data: such as num
2. Add two methods in methods: such as add (increment), sub (decrement)
3. Use v-text to set num to the span tag
4. Use v-on to add, sub Bound to + and - buttons respectively
5. The logic of accumulation: if it is less than 10, it will accumulate, otherwise it will prompt
6. The logic of decrement: if it is greater than 0, it will decrease, otherwise it will prompt.

<body>
    <div id="app">
        <button @click="sub">-</button>
        <span>{
    
    {
    
     num }}</span>
        <button @click="add">+</button>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
    
    
            el:"#app",
            data:{
    
    
                num:1
            },
            methods:{
    
    
                add:function(){
    
    
                    if(this.num < 10){
    
    
                        this.num++;
                    }else{
    
    
                        alert("最大为10,叼毛别点了");
                    }                    
                },
                sub:function(){
    
    
                    if(this.num > 0){
    
    
                        this.num--;
                    }else{
    
    
                        alert("不能为负");
                    }
                }
            }
        })
    </script>
</body>

The result is as follows:

Insert image description here


Things to note are as follows

  • When creating a Vue example: el (mount point), data (data), methods (methods)
  • The function of the v-on instruction is to bind events, abbreviated as @
  • In the method, the data in data is obtained through this and keywords
  • The role of the v-text directive is to set the text value of the element, abbreviated as { {}}

v-show

Insert image description here

The implementation code is as follows: (Everyone understands, you can display or hide certain things according to age)

<body>
    <div id="app">
        <input type="button" value="切换限制级别" @click="man">
        <input type="button" value="切换青少年级别" @click="boy">
        <img v-show="age >= 18" src="https://img1.mydrivers.com/img/20230305/e103b86e-b368-45bb-93aa-8e4d51964fe2.png">
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
    
    
            el:"#app",
            data:{
    
    
                age:16
            },
            methods:{
    
    
                man:function(){
    
    
                    this.age = 18;
                },
                boy:function(){
    
    
                    this.age = 16;
                }
            }
        })
    </script>
</body>

The effect is as shown below

Insert image description here

Back to the topic, its v-show tag essentially switches the display attribute of the style and switches it to none


Precautions

  • The role of the v-show command is to switch the display state of elements according to true and false
  • The principle is to modify the display of the element to achieve display and hiding.
  • The content after the instruction will eventually be parsed as a boolean value
  • Elements with a value of true are displayed, elements with a value of false are hidden.
  • After the data changes, the display status of the corresponding element will be updated synchronously.

v-if

v-if and v-show are actually similar, both are used to control the display or hiding of elements. The syntax is as follows

Insert image description here

demo code

<body>
    <div id="app">
        <p v-if="isShow">叼毛</p>
        <input type="button" value="切换显示" @click="change">
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
    
    
            el:"#app",
            data:{
    
    
                isShow:false
            },
            methods:{
    
    
                change:function(){
    
    
                    this.isShow = !this.isShow;
                }
            }
        })
    </script>
</body>

demo results
Insert image description here

The difference between v-show and v-if is that when switching, v-if will directly remove the tag when it is modified and not displayed, while v-show only changes the status of the style tag.
The following figure can clearly see the changes in the two label modifications when switching.
Insert image description here


Use v-show for frequently switched elements, because v-if will modify the dom tree, and v-show only operates the style, so v-show has better performance, but the hidden elements of v-show will still be displayed, which is unsafe. question.

  • The function of the v-if instruction is to switch the display state of the element based on the true or false expression.
  • The essence is to switch the display state by manipulating dom elements
  • If the value of the expression is true, the element exists in the dom tree, if it is false, it is removed from the dom tree.
  • Frequently switch v-show, otherwise use v-if, the former consumes less switching

v-bind

Syntax: v-bind: attribute name = expression

Insert image description here

This v-bind can also be omitted. As shown below, both methods are possible

<body>
    <div id="app">
        <img v-bind:src="imgSrc" alt="">
        <img :src="imgSrc" alt="" :title="imgtitle+'!!!'">      
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
    
    
            el:"#app",
            data:{
    
    
                imgSrc:"https://img0.baidu.com/it/u=340747937,2651100772&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=889",
                imgtitle:"可可奈奈"
            }
        })
    </script>
</body>

Insert image description here

This title tag will display text when the mouse is hovering. After setting, the title text will be displayed when hovering the second picture, but not the first picture. It can also be seen from the above code that this title can also be spliced ​​into strings.
:title="imgtitle+'!!!'"


<img :src="imgSrc" alt="" :title="imgtitle+'!!!'" :class="{active:isActive}" @click="toggleActive">
The class of this label, that is, whether active takes effect depends on whether isActive is true or false.

Insert image description here


Image switching example

This example combines what we have learned before. It is a good demo. To achieve the effect, click the arrow on the left to switch to the previous picture; click the arrow on the right to switch to the next picture. Hide the left picture on the first picture. Arrow, hide the right arrow on the last image.
Insert image description here

Its implementation steps are as follows

Insert image description here

Explanation: Write JavaScript: void (any number) to prevent the hyperlink from jumping

<body>
  <div id="mask">
    <div class="center">
      <h2 class="title">
        <img src="./images/logo.png" alt="">
      </h2>
      <!-- 图片 -->
      <img :src="imgArr[index]" alt="" />
      <!-- 左箭头 -->
      <a href="javascript:void(0)" v-show="index!=0" @click="prev" class="left">
        <img src="./images/prev.png" alt="" />
      </a>
      <!-- 右箭头 -->
      <a href="javascript:void(0)" v-show="index<imgArr.length-1" @click="next" class="right">
        <img src="./images/next.png" alt="" />
      </a>
    </div>
  </div>

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

  <script>
    var app = new Vue({
    
    
      el: "#mask",
      data: {
    
    
        imgArr: [
          /* 添加图片路径 */
          "./images/00.jpg",
          "./images/01.jpg",
          "./images/02.jpg",
          "./images/03.jpg",
          "./images/04.jpg",
          "./images/05.jpg",
          "./images/06.jpg",
          "./images/07.jpg",
          "./images/08.jpg",
          "./images/09.jpg",
          "./images/10.jpg",
        ],
        /* 数组索引 */
        index: 0
      },
      methods: {
    
    
        prev:function(){
    
    
          this.index--;
        },
        next:function(){
    
    
          this.index++;
        }
      },
    })
  </script>
</body>

v-for

Used to traverse the array to automatically generate a list structure, which can be understood as copy and paste, automatically traverse the array, and bind and display the element data in turn

Analysis as shown below

Insert image description here

Note: The above :titleis using v-bind, setting a tiele attribute for it, but it can be omitted as: title; then { { index}} means to take the array subscript.

Practical usage example:
code first

<body>
    <div id="app">
        <ul>
            <li v-for="item in arr">
                人称:{
    
    {
    
    item}}
            </li>
            
        </ul>
        <h2 v-for="i in food">
            {
    
    {
    
    i.name}}
        </h2>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>

    <script>
        var app = new Vue({
    
    
            el:"#app",
            data:{
    
    
                arr:["你","我","他"],
                food:[
                    {
    
    name:"石头拌稀饭"},
                    {
    
    name:"黄沙炒米饭"}
                ]
            }
        })
    </script>
</body>

The demonstration results are as follows:
Insert image description here

In fact, through the above example, you should understand that the use of v-for means traversing data elements and presenting them in the same format

We are adding two click methods to it,Use the v-on command to bind
Insert image description here
The effect is as follows:
Insert image description here

The principle is very simple: the method of adding food is to add new elements to the array, and then because of the v-for tag, they are all traversed. The
method of subtracting food is the same. Using the shift method, each time the leftmost element of the array is removed, it cannot be traversed. If you reach this element, it will naturally not be displayed.

v-for can help us generate a list very conveniently.

Insert image description here


v-on supplement

Pass custom parameters, event modifiers

Usage example:

Insert image description here

The verification results are as follows:

Insert image description here


Another example, triggering a pop-up window based on the Enter key on the keyboard
Insert image description here

Insert image description here


v-model

Get and set the value of form elements (two-way data binding)

Insert image description here

Demonstration example

Insert image description here

Insert image description here


Insert image description here


axios network request

basic use of axios

When using axios, you need to be connected to the Internet and introduce the basic syntax of the axios online address request library provided by the official website
. It is actually an encapsulation of Ajax.

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

It is divided into two, a callback function that responds to successful execution and a callback function that responds to failed execution, as shown below.

Insert image description here

post请求中,第一个参数是url的地址,第二个参数是post的数据

Let’s use these two interface documents as a demonstration.
Insert image description here

Sample code (not using vue, using native js)

<body>
    <input type="button" value="get请求" class="get">
    <input type="button" value="post请求" class="post">
    <!-- 官网提供的 axios 在线地址 -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script>
        /*
            接口1:随机笑话
            请求地址:https://autumnfish.cn/api/joke/list
            请求方法:get
            请求参数:num(笑话条数,数字)
            响应内容:随机笑话
        */
        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);
              })
        }
        /*
             接口2:用户注册
             请求地址:https://autumnfish.cn/api/user/reg
             请求方法:post
             请求参数:username(用户名,字符串)
             响应内容:注册成功或失败
         */
        document.querySelector(".post").onclick = function () {
    
    
            axios.post("https://autumnfish.cn/api/user/reg",{
    
    username:"盐焗西兰花"})
            .then(function(response){
    
    
                console.log(response);
                console.log(this.skill);
            },function (err) {
    
    
                console.log(err);
              })
          }

    </script>
</body>

Using axios in vue

The core of network data is that part of the data is obtained through the network.So the network request is sent in the method. After the response is successful, the data returned by the server is bound to the corresponding data value.

Trap, ajax is asynchronous, this in the ajax function points to not the vue instance, you cannot get the instance in vue through this, so you will not use this in the axios function

this will change, so the solution is to save it first and define a that, var that = this;

<body>
    <div id="app">
        <input type="button" value="获取笑话" @>
    </div>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        var app = new Vue({
    
    
            el:"#app",
            data:{
    
    
                joke:"很好笑的笑话"
            },
            
            methods:{
    
    
                getJoke:function(){
    
    
                    var that = this;
                    axios.get("https://autumnfish.cn/api/joke").then
                    (function(response){
    
    
                        console.log(response.data);
                        that.joke = response.data;
                    },function(err){
    
     })
                }
            }
        })
    </script>
</body>

Insert image description here

Insert image description here


Guess you like

Origin blog.csdn.net/giveupgivedown/article/details/130934649
Recommended