04-VUE Common Instructions Best Practices

Background analysis

Traditional html does not support definitions of structures such as expressions, branch statements, looping statements, etc. To compensate for the shortcomings of many front-end frameworks, the template engine enhances the functionality of html by adding custom attributes to html elements and then processing html custom attributes with the help of the parsing engine at the bottom.

Common Instructions in Vue

v-bind

In html, if you want the attribute value of an element to change with the content of the program, you can use v-bind or: instead, its basic syntax is as follows:

<element v-bind:Property Name="Variable or js Expression">

It can also be simplified in its basic syntax, such as:

<element :Property Name="Variable or js Expression">

Case Study:

	<div id="app">
		<font :color="color">hello</font>
	</div>
	<script>
		new Vue({
			el:"#app",
			data:{
				color:"red"
			}
		});
	</script>

v-show

v-show is a special instruction for the display and hiding of a specific control element, whose basic syntax is:

<Element v-show="Variable of bool type or js expression returning bool type">

When the Vue object is scanned to v-show, the variable or js expression in "" is executed immediately.
If a variable or a js expression evaluates to true, nothing happens and the element remains intact. If a variable or a js expression evaluates to false, the new Vue() automatically adds display:none to the current element.

The example key code is as follows:

  <style>
    .pop{
      width:300px; height:150px;
      background-color:lightGreen;
    }
    .pop>.close{
      float:right;
      padding:5px 10px;
      cursor:pointer;
    }
  </style>
 <div id="app">
    <button @click="show">show</button>
    <div v-show="display" class="pop">
      <span class="close" @click="hide">×</span>
    </div>
 </div>
  <script>
        //2.Create a new Vue object
        new Vue({
          el:"#app",
          data:{
            display:false
          },
          methods:{
            show(){
              this.display=true;
            },
            hide(){
              this.display=false;
            }
          }
        })
    </script>

v-if and v-else

v-if and v-else are two ways to implement branch control in html. When they are used, the two elements corresponding to v-if and v-else must be written next to each other! No other elements can be inserted in the middle. Their basic syntax is:

<Element 1 v-if="boolean A variable of type or js Expression">
<Element 2 v-else>

The example key code is as follows:

<div id="app">
    <!--First div Is what appears when you are logged in-->
    <div v-if="isLogin"><h3>Welcome, dingding | <a href="javascript:;" @click="logout">Cancellation</a></h3></div>
    <!--The second div Is the content displayed when not logged in-->
    <div v-else><a href="javascript:;" @click="login">Sign in</a> | <a href="javascript:;">register</a></div>
  </div>
  
 <script>
    new Vue({
      el:"#app",
      data:{
        isLogin:false //Starting user is not logged in by default
      },
      methods:{
        login(){
          this.isLogin=true;
        },
        logout(){
          this.isLogin=false;
        }
      }
    })
  </script>

v-else-if

The basic syntax of v-else-if is:

<Element 1 v-if="Condition 1">

<Element 2 v-else-if="Condition 2">

<Element 3 v-else-if="Condition 3">

... ...
<element n v-else>

Note that v-if and v-else-if and v-else must be written together, and no other elements can be inserted.

The example key code is as follows:

<div id="app">
    <span v-if="score>=90">excellent</span>
    <span v-else-if="score>=80">good</span>
    <span v-else-if="score>=70">pass</span>
    <span v-else>pass</span>
 </div>
  <script>
    var vm=new Vue({
      el:"#app",
      data:{
        score:95
      }
    })
    //In console: vm.socre=85
  </script>
 

v-for

v-for is a special instruction designed to repeatedly generate elements of the same structure from the contents of an array. The syntax is:

<Elements to be generated repeatedly v-for="(Current element value, current location) of array">

The example key code is as follows:

<div id="app">
    <!--demand: according to tasks Task lists in arrays generate multiple iterations li-->
    <ul>
      <li v-for="(t,i) of tasks" :key="i">
      {{i+1}} - {{t}}
      </li>
    </ul>
  </div>
 <script>
    var vm=new Vue({
      el:"#app",
      data:{
        //Save to-do list with an array
        tasks:["Having dinner", "Sleep"]
      }
    })
  </script>

v-for can also traverse object properties, such as:

<div id="app">
    <!--demand: ergodic lilei Object, show details of Li Lei's object on the page-->
    <ul>
      <li v-for="(value,key) of lilei" :key="key">
        {{key}} : {{value}}
      </li>
    </ul>
  </div>
  <script>
    var vm=new Vue({
      el:"#app",
      data:{
        lilei:{
          name:"Li Lei",
          age:11
        }
      }
    })
  </script>

v-for can also count, for example:

  <div id="app">
    <ul>
      <li v-for="i of pageCount" :key="i">{{i}}</li>
    </ul>
  </div>
  <script>
    new Vue({
      el:"#app",
      data:{
        pageCount:5 //Five pages in total
      }
    })
  </script>

v-on

v-on is a directive that binds event handlers specifically. Its basic syntax is:

<element v-on:Event Name="Event Handler Function Name()">

v-on can also be replaced with the @ symbol, whose basic grammatical structure is:

 <element @Event Name="Event Handler Function Name()
 

If the event handler does not need to pass in an argument value, then () can also be omitted, for example:

<element @Event Name="Event Handler Function Name">

Any event handler defined on the page adds the corresponding function entity to the method member in the new Vue().

The example key code is as follows:

<div id="app">
<!--Which to Point div,Which one? div You can call yourself pain!-->
<div id="d1" @click="say('html')">d1</div>
<div id="d2" @click="say('css')">d2</div>
</div>
  
 <script>
    new Vue({
      el:"#app",
      methods:{
        say(name){
          console.log(`hello ${name}!`)
        }
      }
    })
  <script>

v-html

If {{}} is bound to an HTML fragment, it will not be parsed by the browser. Instead, the content of the HTML fragment will be displayed as is - the same as the textContent in the DOM. If you want HTML to be parsed, you can use v-html instead of {}. Its basic syntax structure is:

 <element v-html="variable"> This location shows variable content </element>

The example key code is as follows:

 <div id="app">
    <h3>{{msg}}</h3>
    <h3 v-html="msg"></h3>
  </div>
  <script>
    new Vue({
      el:"#app",
      data:{
        msg:`Come from&lt;&lt;<a href="javascript:;">Xinhua News Agency</a>&gt;&gt;Message`
      }
    })
  </script>

v-text

v-text is a special instruction that can be used instead of {{}} binding element content to set the text content inside the element and to prevent the temporary display of {{}} due to network latency. Its syntax is:

<element v-text="Variable or js Expression"> </element>

The example key code is as follows:

  <div id="app">
            <!--js The sky         -->
    <h3 v-text=`User name:${uname}`></h3>
            <!--js The sky         -->
    <h3 v-text=`integral:${score}`></h3>
  </div>
  <script>
    setTimeout(function(){
      new Vue({
        el:"#app",
        data:{
          uname:"dingding",
          score:1000
        }
      })
    },6000)
  </script>

v-model

v-model is a directive used to implement two-way binding, which can update changes in the program to the page (model->view) automatically, and changes on the page back to the variables in the program (view->model), the basic syntax of which is:

<Form Elements v-model:value="variable">

The example key code is as follows:

 <div id="app">
    <!--One-way Binding: (Model->View cannot View->Model)-->
    <!-- <input :value="keyword"> -->
    <!--Binding in both directions: (Model->View Again View->Model)-->
    <input v-model:value="keyword">
    <button @click="doUpdate">To update</button>
  </div>
  <script>
    var vm=new Vue({
      el:"#app",
      data:{
        keyword:"ABC" //Starting user did not enter any keywords
      },
      methods:{
        doUpdate(){
          console.log(`lookup ${this.keyword} Related Content...`)
        }
      }
    })
  <script>

Two-way binding for radio operations:

The value of a radio operation is a fixed write-dead alternative! When a user switches the selected state before a different radios, the value of the checked property of the radios is actually changed. Therefore, to get the value of the currently selected radios using a two-way binding, the checked property should be bound:

<input type="radio" value="Fixed Value" v-model:checked="variable">

The sample code is as follows:

<div id="app">
    Gender:
    <label><input type="radio" name="sex" value="1" v-model:checked="sex">male</label>
    <label><input type="radio" name="sex" value="0" v-model:checked="sex">female</label>
    <h3>The gender you selected is:{{sex==1?"male":"female"}}</h3>
 </div>
 <script>
    new Vue({
      el:"#app",
      data:{
        sex:1
      }
    })
 </script>
  

Binding of select elements in both directions

A select contains multiple option elements. All alternative values are distributed on each option. However, each alternative value value is also written to death. Each time a user selects a different option, the select element actually modifies the value of the selected option to the value property of the select. The syntax is:

<select v-model:value="variable">
 <option value="Value 1">xxx</option>

 ... ...

 ... ...
</select>

The sample code is as follows:

 <div id="app">
    <select v-model:value="src">
      <option value="beijing">Beijing</option>
      <option value="shanghai">Shanghai</option>
      <option value="hangzhou">Hangzhou</option>
    </select><br/>
    <img :src="src">
  </div>
  <script>
    new Vue({
      el:"#app",
      data:{
        src:"beijing"
      }
    })
  </script>

Summary

This subsection mainly analyses some instruction elements commonly used in vue, which can be skilled in the process of understanding and application by referring to this document and official documents combined with practice.

Keywords: html5 Vue.js html

Added by exec1 on Thu, 09 Sep 2021 02:00:13 +0300