The basics you must know in Vue

Posted by orudie on Tue, 01 Mar 2022 09:19:34 +0100

Template grammar

  • An instruction is a special attribute with a v-prefix. The attribute value of the directive is expected to be a single JavaScript expression

Text Rendering

{{}} syntax

const app = Vue.createApp({
  data() {return { msg: 'Hello Vue3' } }
})
const vm = app.mount('#app')

v-text instruction and v-html instruction

<div v-html="raw"></div>


<div v-text="raw"></div>
<div >{{raw}}</div>

2, Conditional rendering

v-if conditional rendering

<div v-if="isLogin">Hello, Mu Mu!</div>

//You can also use v-else
<div v-else>Please operate after login</div>

v-else-if multi conditional rendering

<div id="app">
	<div v-if="score>=90">excellent</div>
	<div v-else-if="score>=80">good</div>
	<div v-else-if="score>=70">secondary</div>
	<div v-else-if="score>=60">pass</div>
	<div v-else>Fail, man, you need to work hard!</div>
</div>

Another option for displaying elements based on conditions is the v-show instruction

v-show conditional rendering

<div v-show="canShow">I like you!</div>

Difference between v-show and v-if

v-show CSS method hiding

v-if# remove dom node mode hiding

For frequent switching, use v-show, and vice versa

3, List rendering

  v-for 

We use the v-for instruction to render according to the option list of a set of arrays. The v-for instruction requires a special syntax in the form of item in items. Items is the source data array and item is the alias of the array element iteration.

<li v-for="item in items">
   {{item}}
</li>
data(){
      return {items:['angular','react','vue','jquery']}
}

You can also use v-for to traverse the properties of an object.

<li v-for="value in obj">
   {{value}}
</li>

data(){
      return {obj:{title:"Vue3.0 introduction",author:"Wood",pdate:"2022-3-1"}}
}

v-for # index

v-for also supports an optional second parameter, the index of the current item.

<li v-for="(item,index) in items" >
   {{index}}-{{item}}
</li>
data(){
      return {items:['angular','react','vue',jquery]}
}

v-for # unique identifier key

In order to give Vue a hint so that it can track the identity of each node and reuse and reorder existing elements, you need to provide a unique key for each item

<li v-for="(item,index) in items"  key="item.id" >
...
</li>

It is not recommended to use index as the value of key (as long as the value of key is unique)

Use v-for with v-if

Note that we do not recommend using v-if and v-for on the same element

You can correct it by moving v-for to the < template > tab:

<template v-for="todo in todos" :key="todo.name">
  <li v-if="!todo.done">
    {{ todo.name }}
  </li>
</template>

4, Events

Listening events

We can use the v-on instruction (usually abbreviated as the @ symbol) to listen for DOM events and execute some JavaScript when the event is triggered.

<button @click="counter++">{{counter}}</button>
<button v-on:click="counter--">{{counter}}</button>


Vue.createApp({
  data() {
    return {   counter: 1   }
  }
}).mount('#app')

Event handling method

Many event processing logic will be more complex, so it is not feasible to write JavaScript code directly in v-on instructions. Therefore, v-on can also receive a method name that needs to be called.

<button @click="greet">to greet</button>

Vue.createApp({
    data(){return{name:'vue'}},
    methods: {
        greet(event){
            alert('Hello'+this.name)
       } 
    }  
}).mount('#app')

Method in inline processor

In addition to being directly bound to a method, you can also call the method in the inline JavaScript statement:

<button @click="say('Hello')">Hello</button>
<button @click="say('have you eaten')">Greeting dinner</button>

Vue.createApp({
        methods:{
            say(msg){alert(msg)}
        }  
}).mount('#app')

Event modifier

Prevent event bubbling and block default events

Vue.js provides event modifiers for v-on. A modifier is represented by an instruction suffix beginning with a dot.

<div @click="showMe" style="padding: 50px;">
    <!-- Prevent click events from continuing to bubble -->
    <div class="son" @click.stop="showMe" style="background-color: #dbffd0; "> prevent event bubbling < / div >
    <!-- Click event without jumping -->
    <a @click.prevent="showMe" href="http://baidu. Com "> Baidu < / form >
   <!-- Modifiers can be concatenated -->
    <a @click.stop.prevent="showMe"  href="http://baidu. Com "> tandem</a>
    <!-- Execute only once -->
    <button @click.once="showMe">I love you!</button>
</div>

methods:{
    showMe(event){ alert(event.target.innerHTML) }

Key modifier

When monitoring keyboard events, we often need to check specific keys. You can use key modifiers

<!-- Only in `key` yes `Enter` Time call `vm.submit()` -->
<input @keyup.enter="submit" />

5, Form binding

Text and multiline text

//text
<input v-model="msg" />
<p>{{ msg }}</p>

//Multiline text
<p style="white-space: pre-line;">{{ msg2 }}</p>
<br />
<textarea v-model="msg2" ></textarea>

Check box

Single check box

<input type="checkbox" id="checkbox" v-model="checked" />
<label for="checkbox">{{ checked }}</label>

Multiple check boxes

<div id="app">
  <input type="checkbox" id="name1" value="Wood" v-model="checkedNames">
  <label for="name1">Wood</label>
  <input type="checkbox" id="name2" value="every day" v-model="checkedNames">
  <label for="name2">every day</label>
  <input type="checkbox" id="name3" value="mumu" v-model="checkedNames">
  <label for="name3">mumu</label>
  <br>
  <span>The selected name is: {{ checkedNames }}</span>
</div>

data() {
    return {
      checkedNames: []
    }

Radio box

 <label><input type="radio" value="1"  v-model="sex">male</label>
 <label><input type="radio" value="2"   v-model="sex">female</label>
 <label><input type="radio" value="3"   v-model="sex">secrecy</label>
<p>{{sex}}</p>

data() {
    return {
     sex:1
    }

Selection box

<div id="v-model-select" class="demo">
  <select v-model="selected">
    <option disabled value="">Please select</option>
    <option value="A">Preschool</option>
    <option value="B">primary school</option>
    <option value="C">junior high school</option>
  </select>
<p>{{select}}</p>

Value binding

<input type="checkbox" v-model="toggle" true-value="yes" false-value="no" />

<input type="radio" v-model="pick" v-bind:value="a" />

<select v-model="selected">
  <!-- Inline object literal -->
  <option :value="{ number: 123 }">123</option>
</select>

Form modifier

// .lazy
// You can add the lazy modifier to switch to synchronization after the change event
<!-- In“ change"Sometimes not“ input"Update when -->
<input v-model.lazy="msg" />

// .number
// If you want to automatically convert the user's input value to numeric type, you can add the number modifier to the v-model:

<input v-model.number="age" type="text" />

// . trim filter leading and trailing blanks
<input v-model.trim="msg" />

6, Calculated

For any complex logic that contains responsive data, you should use computational properties (calculate new data from existing data)

const app = Vue.createApp({
    computed: {		 
        rmsg: function() {						 
            return this.msg.split('').reverse().join('')
        }
    }
}).mount("#app")


<p>Calculate flipped information: {{ rmsg }}</p>

7, watch monitor

While computing properties is more appropriate in most cases, sometimes a custom listener is needed, which is most useful when asynchronous or expensive operations need to be performed when data changes.

watch:{
    num(nval,oval){
        console.log(nval,oval)
    }	 
}

The reference data type needs to add processor handler and deep

watch:{
    person:{
        handler(state){
            console.log(state);
            localStorage.setItem("age",this.person.age);
        },
        deep:true
    }
}

8, Built in instruction

In addition to the default built-in instructions for core functions (such as v-model and v-show), Vue also allows you to register custom instructions.

You still need to perform low-level operations on ordinary DOM elements, and custom instructions will be used at this time.

Global registration

// Global registration
<div id="app">
	<input type="text" v-focus>
</div>
<script>
	const app = Vue.createApp({ 
	})
	app.directive('focus', {
	  // When the bound element is mounted in the DOM
	  mounted(el) {
		el.focus() // Focus element
	  }
	})
	app.mount("#app")
</script>

Local registration

const app = Vue.createApp({ 		
    directives: {
         focus: {
            // Definition of instruction
            mounted(el) {
                 el.focus()
	}
         }
    }
}).mount("#app")

Topics: Javascript Front-end Vue.js