VUE common instructions

3, Common instructions

1,v-cloak

Function: solve the flash problem caused by the time difference when the browser loads the page

Principle: first hide the element mounting position, and then display the final result after processing the rendering

Note: it needs to be used with CSS rules

Example:

<style>
    [v-cloak] {
        display: none;
    }
</style>

<div v-cloak>
  {{ message }}
</div

If multiple elements need to solve the flicker problem later, you can write v-cloak on the root element.

2. Data binding instruction

  • v-text fill in plain text
    • Compared with interpolation expression, it is more concise
    • There is no flicker problem of interpolation expression
<div id='app'>
	<span v-text="msg"></span>
	<!-- Same as below -->
	<span>{{msg}}</span>
</div>

<script src="./js/vue.js"></script>
<script>
  new Vue({
    el: '#app',
    data: {
      msg:'<a href="http://www.baidu. COM / "> Baidu < / a > '
    }
  })
</script>
  • v-html fill HTML fragment
    • There are safety problems
    • The internal data of this website can be used, but the data from third parties cannot be used
<div id='app'>
    <div v-html="html"></div>
</div>

<script src="./js/vue.js"></script>
<script>
  new Vue({
    el: '#app',
    data: {
      html:'<a href="http://www.baidu. COM / "> Baidu < / a > '
    }
  })
</script>
  • v-pre fills in the original information
    • Skip the compilation of the expression and display the original information
<span v-pre>{{ this will not be compiled }}</span>

Sometimes we don't want the expression in the instruction to run. We just need to put quotation marks on the expression. For example:

<div v-html='"msg"'></div>

3,v-once

Function: render elements and components only once, and then elements and components will lose their responsive (data level) function

Q & A: how to understand responsive?

  • Layout responsive: change the layout as the screen size of the terminal device changes
  • Data response: after the data changes, the page changes, the data in the page changes, and the data in the code changes (two-way data binding)

Example:

<div id="app">
	<h3>{{message}}</h3>
	<!-- Dynamic modification message Value, this binding will not change -->
	<div v-once>{{message}}</div>
</div>
<script src="./js/vue.js"></script>
<script type='javascript'>
  const vm = new Vue({
      el: '#app',
      data: {
          message: 'Hello world'
      }
  })
</script>

##4,v-bind

Function: dynamically bind one or more attribute s [in component: one declaration, multiple uses]

Scenario: it will be used when reusing some data. For example: Flying Pig official website

<!-- v-bind binding href Attribute value -->
<a v-bind:href='url' v-bind:target='type'>Jump</a>

<!-- v-bind binding href Attribute value (short form) -->
<a :href='url' :target='type'>Jump</a>

Sample code

<body>
    <div id="app">
        <a :href="url" :target="type" :alt="alt">{{alt}}</a>
        <a :href="url">{{alt}}</a>
    </div>
</body>
<script src="./js/vue.js"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            url: 'https://www.fliggy.com/',
            type: '_blank',
            alt: 'Flying pig official website'
        }
    })
</script>

5. v-on (key)

5.1 basic use

Function: bind event listener (event binding)

Example:

<!-- Conventional writing -->
<button v-on:click="num++"></button>
<!-- abbreviation -->
<button @click="num++"></button>

<!-- Event handler function call: write function name directly -->
<button @click="say"></button>
<!-- Event handler function call: general call -->
<button @click="alert('123')"></button>

If the event handling function is a user-defined function, it needs to be defined first. The definition method is as follows:

...
data: {
    ...
},
methods: {
    functionName: function(arg1,arg2,arg3,...){
        // something to do
    },
    ....
}

Note: in the event binding v-on attribute expression, remember not to write business logic directly, for example, @ click="alert('123 ')"

Event handler parameters

<!-- Event handler function call: write function name directly -->
<button @click="say"></button>

<!-- Event handler function call: general call -->
<button @click="say('hi',$event)"></button>

When user-defined parameters are not passed, the above two usages can be used; However, if you need to pass custom parameters, you need to use the second method.

Attention points of event object transmission and reception

  • If the event uses the function name directly and does not write parentheses, the event object is passed as a unique parameter by default
  • If you use a regular custom function call (as long as you write parentheses), if you need to use an event object, it must be passed as the last parameter, and the name of the event object must be "$event"

Sample code

<style>
    #big {
        width: 300px;
        height: 300px;
        background-color: red;
    }
    #mid {
        width: 200px;
        height: 200px;
        background-color: green;
    }
    #sma {
        width: 100px;
        height: 100px;
        background-color: pink;
    }
</style>

<body>
    <div id="app">
        <div id="big" @click="say('Big baby',$event)">
            <div id="mid" @click="say('Er wa',$event)">
                <div id="sma" @click="say('Three children',$event)"></div>
            </div>
        </div>
    </div>
</body>

<script src="./js/vue.js"></script>
<script>
    new Vue({
        el: '#app',
        data: {

        },
        methods:{
            say: function(name,event){
                console.log('Did you order' + name);
            }
        }
    })
</script>

5.2 event modifier

Meaning: a specific behavior used to handle events

Use example:

<!-- Stop bubbling -->
<button @click.stop="doThis"></button>
<!-- Block default behavior -->
<button @click.prevent="doThis"></button>
<!--  Concatenation modifier -->
<button @click.stop.prevent="doThis"></button>

For more event modifiers, please refer to the official documentation: https://cn.vuejs.org/v2/api/#v-on

5.3 key modifier

When monitoring keyboard events, we often need to check the detailed keys. Vue allows you to add key modifiers for v-on when listening for keyboard events.

<!-- Only in `key` yes `Enter` Called when the Enter key is pressed -->
<input v-on:keyup.enter="submit">

<!-- Only in `key` yes `Delete` Called when the Enter key is pressed -->
<input v-on:keyup.delete="handle">

For more key modifiers, please refer to the official document: https://cn.vuejs.org/v2/guide/events.html#%E6%8C%89%E9%94%AE%E4%BF%AE%E9%A5%B0%E7%AC%A6

5.4. Custom modifier (understand)

There is another additional detail to note about the key modifier. The built-in key modifier of Vue is limited. If the modifier of other keyboard keys is needed, we can use the global object config Keycodes defines their own key modifiers, for example:

Vue.config.keyCodes.KEYNAME = 112

Of course, in actual use, it also allows us to directly use the number (key code) corresponding to the key without defining the modifier, for example:

<input v-on:keyup.13="submit">

However, it is not very convenient to directly remember the relationship between numbers and keys in this way. It has been officially abandoned and may not be supported in the latest browsers. Reference address: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode

6. Circular branch instruction

6.1. Cycle command

Function: render according to the option list of a set of arrays or objects.

Instruction: v-for

  • Example of array traversal:
<!-- Template part -->
<ul>
    <!-- Direct value -->
    <li v-for='item in fruits'>{{item}}</li>
    <!-- tape index -->
    <li v-for='(item,index) in fruits'>{{item}}{{index}}</li>
</ul>

<!-- JavaScript part -->
......
data: {
	fruits: ['apple','pear','banana','orange']
}
......

Details: the function of key can improve the performance without affecting the display effect (if there is no id, you can consider using index instead)

<ul>
    <li :key='item.id' v-for='(item,index) in fruits'>{{item}}</li>
</ul>
  • Object traversal example:
<!-- Template part -->
<ul>
    <li v-for='(value,key,index) in obj'>{{value + '-' + key + '-' + index}}</li>
</ul>

<!-- JavaScript part -->
......
data: {
	obj: {
		username: 'zhangsan',
		age: 28,
		gender: 'male'
	}
}
......

Example code:

<body>
    <div id="app">
        <div>
            <ul>
                <li :key="index" v-for="(item,index) in cars">{{item}}</li>
            </ul>
        </div>
        <div>
            <ul>
                <li :key="index" v-for="(item,key,index) in user">{{key}}: {{item}}</li>
            </ul>
        </div>
    </div>
</body>
<script src="./js/vue.js"></script>
<script>
    new Vue({
        el: '#app',
        data: {
            cars: ['bmw','aodi','benci','haima'],
            user: {
                username: 'zhangsan',
                gender: 'mele',//Gender, sex
                age: 22
            }
        }
    })
</script>

###6.2 branch instruction

Function: judge whether to render the element according to the Boolean value (true/false) of the expression

  • v-if
  • v-else
  • v-else-if

The above three instructions are the most common in branches. According to the requirements, v-if can be used alone, together with v-else, or together with v-else-if and v-else.

  • v-show

v-show switches the display CSS attribute of an element according to the true or false value of the expression.

Use example:

<!-- Template part -->
<div v-if="score >= 90">
  excellent
</div>
<div v-else-if="score >= 80 && score < 90">
  good
</div>
<div v-else-if="score >= 70 && score < 80">
  commonly
</div>
<div v-else>
  fail,
</div>
<!-- v-show -->
<div v-show='flag'>test v-show</div>

<!-- JavaScript part -->
......
data: {
	score: 88,
	flag:false
}
......

Thinking: what is the difference between v-if series and v-show?

v-if: controls whether elements are rendered

v-show: controls whether elements are displayed (rendered, display:none;)

v-if series instructions and v-show instructions can be combined with v-for instructions (loop + branch). For example:

<ul>
    <li v-for='(v,k,i) in obj' v-show='v==25'>{{v}}</li>
</ul>

7. Comprehensive case: simple shopping cart

Case effect

Details:

  • Display basic product information
  • Calculate subtotal for each item
  • Addition and subtraction of commodity quantity
    • +: increase the quantity of goods and update the subtotal at the same time
    • -: reduce commodity proficiency and update the subtotal at the same time. If it is "1", then click - to remove the commodity

If you need to access the data in your own data attribute in the Vue instance, you can use the following methods:

  • this.xxxxx
  • this.$data.xxxxx
  • this._data.xxxxx

Reference data source

var cartData = [
    {
        id: 1,
        name: 'millet',
        price: 100,
        num: 1
    },
    {
        id: 2,
        name: 'Huawei',
        price: 200,
        num: 1
    },
    {
        id: 3,
        name: 'association',
        price: 300,
        num: 1
    }
]

Reference core code

<body>
    <div id="app">
        <ul>
            <li v-for="(item,index) in cartData" style="list-style: none;">
                commodity ID: {{item.id}}&emsp;&emsp;
                Trade name:{{item.name}}&emsp;&emsp;
                Commodity price:{{item.price}}&emsp;&emsp;
                Quantity of goods:<button @click="dec(item,index)">-</button>{{item.num}}<button @click="inc(item)">+</button>&emsp;&emsp;
                Subtotal of goods:{{item.price * item.num}}
            </li>
        </ul>
    </div>
</body>

<script src="./js/vue.js"></script>
<script>
    var cartData = [
        {id:1,name:'Apple',num:1,price:100},
        {id:2,name:'millet',num:1,price:200},
        {id:3,name:'Huawei',num:1,price:300},
    ]

    new Vue({
        el: '#app',
        data: {
            cartData
        },
        methods: {
            dec: function (item,index) {
                // Judge whether it is 1 piece
                if(item.num == 1){
                    confirm('You can't miss it. Are you sure you don't want to buy one?') && this.cartData.splice(index,1)
                }else{
                    item.num--
                }
            },
            inc: function (item) {
                item.num++
            }
        }
    })
</script>

  Represents tab, one top four & nbsp;

8. Style binding

8.1. class style binding

  • Object syntax (used to control switch switching)
<style>
/* CSS fragment */
.active {
	color: red;
}
</style>

<!-- HTML fragment -->
<div v-bind:class="{active: isActive}">class style</div>

<script type='text/javascript'>
// JavaScript fragment
data: {
	isActive: true
}
</script>
  • Array writing
<style>
/* CSS fragment */
.active {
	color: red;
}
</style>

<!-- HTML fragment -->
<div v-bind:class="[activeClass]">Array writing</div>

<script type='text/javascript'>
// JavaScript fragment
data: {
	activeClass: 'active'
}
</script>

8.2 style processing

  • Object syntax
<!-- HTML fragment -->
<div:style="{color: redColor, fontSize: '20px'}">Object writing</div>

<script type='text/javascript'>
// JavaScript fragment
data: {
	redColor: 'red'
}
</script>
  • Array syntax
<!-- HTML fragment -->
<div v-bind:style="[color, fontSize]">Array writing</div>

<script type='text/javascript'>
// JavaScript fragment
data: {
	color: {
		color: 'red'
	},
	fontSize: {
		'font-size': '20px'
	}
}
</script>

9. v-model (key)

Function: the binding of form elements realizes two-way data binding, and the data can be changed through form items.

v-model will ignore the initial values of the value, checked and selected attributes of all form elements, and always take the data of Vue instances as the data source. The initial values should be declared in the data option.

  • Use on normal text boxes
<div id='app'>
    <p>{{message}}</p>
    <input type='text' v-model='message'>

    <!--
    v-model Actually`Grammar sugar`,It is short for the following way of writing
    Syntax sugar: this syntax has no effect on the function of the language, but it is more convenient for programmers to use
    -->
    <input type='text' :value='msg' @input='msg=$event.target.value'/>
</div>

<script type='text/javascript'>
new Vue({
    el: '#app',
    data: {
		msg: 'message Default value'
    }
})
</script>
  • Use on multiline text boxes
<div id='app'>
    <textarea v-model="message"></textarea>
</div>

<script type='text/javascript'>
new Vue({
	el: '#app',
	data: {
		message: 'I am multiline text content'
	}
})
</script>

Note: it is invalid to use interpolation expression in multi line text box (at this time, it can only accept data and cannot change data)

  • Use on a single check box
<div id='app'>
    <input type="checkbox" v-model="checked">
</div>

<script type='text/javascript'>
new Vue({
	el: '#app',
	data:{
		checked:true
	}
})
</script>
  • Use on multiple check boxes
<div id='app'>
    <input type="checkbox" value="html" v-model="checkedNames">
    <input type="checkbox" value="css" v-model="checkedNames">
    <input type="checkbox" value="js" v-model="checkedNames">
</div>

<script type='text/javascript'>
new Vue({
	el: '#app',
	data:{
    	// If there is a corresponding value value in the array, this checkbox will be selected
		checkedNames:[]
	}
})
</script>

Note: this usage requires the input tag to provide the value attribute, and the case of the attribute should be consistent with that of the array element

  • Use on radio buttons
<div id='app'>
    male<input type="radio" name="sex" value="male" v-model="sex">
	female<input type="radio" name="sex" value="female" v-model="sex">
</div>

<script type='text/javascript'>
new Vue({
	el: '#app',
	data: {
		sex: 'female'
	}
})
</script>
  • Use on drop-down box
<div id='app'>
    <select v-model="selected">
        <option>Please select</option>
        <option>HTML</option>
        <option>CSS</option>
        <option>JS</option>
    </select>
</div>

<script type='text/javascript'>
new Vue({
	el: '#app',
	data: {
		selected: 'JS'
	}
})
</script>
  • Modifier

. lazy: by default, Vue's data synchronization adopts the input event Lazy changes it to trigger when it loses focus

. number: automatically convert the user's input value to numeric type (if possible)

. trim: automatically filter the first and last blank characters entered by the user

Note: This article is compiled by Mr. Yang Dingyuan of Qianfeng, which is borrowed here

Tags: Javascript Vue.js

Posted by nariman on Mon, 16 May 2022 18:37:53 +0300