Serial directory address

  • I. Overview of basic knowledge
    • Chapter 1 – Some Basic Concepts posted at 2018-10-31
    • Chapter 2 – The use of common instructions (posted at 2018-11-01)

preface

In the previous chapter, we looked at some of the basic concepts that we often encounter when developing with Vue. Unlike traditional front-end development, Vue eliminates the need for JavaScript to manipulate DOM elements (it still works, but it’s highly recommended). At the heart of this excellent feature is Vue’s instruction system. In this chapter, learn about Vue’s instruction system.

Storage address: Chapter01-rookie Directives

Dry goods collection

1, v – cloak

In the process of using Vue, when we import the vue.js file, there is a Vue object in the browser memory. At this point, we can create a Vue object instance through the constructor, and then we can operate on the instance.

If during this process the reference to vue.js is not loaded for some reason, at this point the uncompiled Mustache tag will not display properly. For example, in the example below, when we simulate slowing down the loading of a web page, you can see that the page will initially display the interpolation, and only after vue.js is loaded will it render the correct data.

<div id="app">
    <p>{{msg}}</p>
</div>

<script src=".. /lib/vue.js"></script>

<script>
    new Vue({
        el: '#app',
        data: {
            msg: 'hello world'}});</script>
Copy the code

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

<div id="app">
	<! -- Add vloak -->
    <p v-cloak>{{msg}}</p>
</div>
Copy the code

As you can see, a V-cloak attribute is added to the P tag when nothing is displayed on the page. As you can see from the style on the right, the CLOAK attribute is removed from the P tag when the load is complete, and the interpolation is compiled and displayed correctly.

2. V-text vs. V-HTML

Both v-text and V-HTML directives update the content of page elements. The difference is that V-text updates the data as string text, whereas V-HTML updates the data as HTML tags.

In updating data, we can also use difference expression to update data. Different from V-text and V-HTML instructions, difference expression will only update the data content where the original placeholder interpolation is, while V-text and V-HTML instructions will replace the whole content.

<div id="app">

	<p>+++++++++ {{msg}} -----------</p>
	<p v-text="msg">= = = = = = = = = = = = = = = = =</p>
	<p v-text="msgHtml">= = = = = = = = = = = = = =</p>
	
	<p v-html="msgHtml">= = = = = = = = = = = =</p>

</div>

<script>
    new Vue({
        el: '#app',
        data: {
            msg: 'hello world',
            msgHtml: '<h3 style="color:green">I want to learn vue.js</h3>'}});</script>
Copy the code

3, v – bind

V-bind can be used to bind a tag’s attributes (e.g., the SRC attribute of img, the title attribute, and so on) to a style (either inline style or class style). At the same time, the bound content is a JS variable, so we can write a legal JS expression for the content.

In the following example, the title and style of the button are both bound by the V-bind directive. For the style binding, we need to build an object. The other style binding methods will be covered later.

<div id="app">
    <! -- v-bind: can be used to bind the attributes and styles of the tag to the tag. For the content to be bound, you can write a valid JS expression.
    <! -- <input type="button" value=" v-bind:title="msgTitle + 'lalala'" v-bind:style="{color:colorStyle,width:widthStyle+'px'}"> -->

    <! -- Use: abbreviation -->
    <input type="button" value="Button" :title="msgTitle + 'lalala'" :style="{color:colorStyle,width:widthStyle+'px'}">
</div>

<script>
new Vue({
    el: '#app',
    data: {
        msgTitle: 'This is my custom title property.',
		colorStyle: 'red',
        widthStyle: '120'}});</script>
Copy the code

The effect is shown as follows:

4, the v – on

In traditional front-end development, when we want to bind an event to a button, we need to retrieve the DOM element of the button and bind the event to the DOM. In the process of learning VUE, we can uphold the idea that for THE DOM operation, let VUE complete for us, we only focus on the business code implementation, therefore, we can use the BUILT-IN V-ON instruction of VUE to complete the binding of events for us. The traditional element JS is written as follows

<input type="button" value="Click on me." id="btn">

<script>
    // The traditional event binding method
    document.getElementById('btn').onclick = function () {
        alert('Traditional event binding method');
    }
</script>
Copy the code

When we bind events using the V-ON directive, we need to specify the v-ON :event(click, mouseDown, mouseup, and so on) bound events on the label.

<input type="button" value="Click on me." id="btn" v-on:click="alert(1111)">
Copy the code

Is that all? Vue reminds us that a property or method is not defined in the vUE instance. It turns out that in the design of vUE, a lot of event handling logic is more complex, so it is not feasible to write JavaScript code directly in the V-ON directive. So V-ON can also receive a method name that needs to be called. Therefore, we need to write the methods under the methods of the Vue instance.

<input type="button" value="Click on me." id="btn" v-on:click="handlerClick">

<! -- use @ for short -->
<input type="button" value="Click on me." id="btn" @click="handlerClickWithParam(1)">Var vm = new Vue({el: '#app', data: {msgTitle: 'this is my custom title ', colorStyle: 'red', widthStyle: '120'}, methods: {// Define all accessible methods of the current vue instance in methods handlerClick() {alert(' I am an event bound with the V-ON directive '); }, handlerClickWithParam(id) {alert(' I am using the v-ON binding event, method argument '+ ID); }}});Copy the code

5, v – model

In previous studies, data binding, whether interpolation or V-text instruction is used, is one-way for the interaction between data, that is, only the value in the VUE instance can be passed to the page, but any operation of the data value on the page cannot be passed to the Model.

For example, in the example page below, we manually modify the contents in the H3 TAB of the page, retrieve the data in the Vue instance through the console, and find that the data has not changed. We can use window.vm to get the vue instance, because the vue object is automatically created in the browser memory after we introduce vue.js. The vue instance created by the constructor is also in the browser memory.

<div id="app">
    <h3>{{ msg }}</h3>
</div>

<script>
    var vm = new Vue({
        el: '#app',
        data: {
            msg: 'Hello, Hahaha.'}});</script>
Copy the code

We know that only form elements can interact with the user, so we can only use v-Model directives to create bi-directional bindings on form controls or components. Bidirectional binding of components will also be covered later.

<div id="app">
    <h3>{{ msg }}</h3>

    <input type="text" name="" id="" v-model:value="msg">
</div>

<script>
    var vm = new Vue({
        el: '#app',
        data: {
            msg: 'Hello, Cheng 16.'}});</script>
Copy the code

6. V-if and V-show

Both the V-if and V-show directives determine whether elements are displayed based on the expression’s true or false values.

In the following code, we modify the flag value by binding a button click event, so as to control the display of the two H3 labels.

<div id="app">
    <input type="button" value="Switch" @click="handlerClick">

    <h3 v-if="flag">I am controlled by the V-if command</h3>
    <h3 v-show="flag">I am using the V-show command control ~~~</h3>
</div>

<script>
    var vm = new Vue({
        el: '#app',
        data: {
            flag: true
        },
        methods: {
            handlerClick() {
                this.flag = !this.flag; }}});</script>
Copy the code

7, v – for

Whether we are writing C#, JAVA or front-end JavaScript, the first thing that comes to mind when we think of looping data is the for loop. Similarly, in vue, the author also provides us with the v-for directive to loop data.

With the V-for directive, we can loop through arrays, objects, numbers, and strings to get each value of the source data. With the v-for directive, you must use the special syntax alias in expression to provide an alias for the currently iterated element, similar to the loop format of foreach in C#.

<div id="app">
    <! -- loop array data -->
    <p v-for="(item,index) in arrayList" :key="index">Array index value: {{index}}, data value: {{item}}</p>
</div>

<script>
    var vm = new Vue({
        el: '#app',
        data: {
            arrayList: [12.20.34.1.6]}});</script>
Copy the code

In the V-for directive, we have full access to the parent scope properties. V-for also supports an optional second argument to the index of the current item. In the above circular array code, item represents each item in the array and index represents the index of the current item, so we can easily print out each item and index in the array. At the same time, we bind a key attribute on the UL tag, which provides a key value for each item in the loop. We can understand that each item in the database table has a unique primary key value. Similarly, we need to ensure that this key value is unique to the current item.

Here, the problem of the key property being unique is explained by looping through an array object.

<div id="app">
     <! Loop object array data -->
	<input type="radio" name="" id="">
    <p v-for="(item,index) in objList" :key="index">Array index value: {{index}}, id: {{item. Id}}, name: {{item. The name}}, age: {{item. Age}}</p>
</div>

<script>
    var vm = new Vue({
        el: '#app',
        data: {
            objList: [
                    {id: 1,name: 'zhangsan',age: 23},
                    {id: 2,name: 'lisi',age: 32},
                    {id: 3,name: 'wangwu',age: 22}]}});</script>
Copy the code

We now loop through an array of objects and add a single box to the front of each item. Now we select the {id: 2,name: ‘lisi’,age: 32} data object and use the console to add new elements to the array. We know that we can add elements to an array using push or unshift, so let’s try that.

<div id="app">
    <! Loop object array data -->
	<input type="radio" name="" id="">
    <p v-for="(item,index) in objList" :key="item.id">Array index value: {{index}}, id: {{item. Id}}, name: {{item. The name}}, age: {{item. Age}}</p>
</div>
Copy the code

The loop for objects, numbers and strings is similar to the loop for arrays. The implementation method is shown below. You can write your own try. When traversing an Object, however, the result of object.keys () is traversed, but there is no guarantee that the result will be consistent across different JavaScript engines.

<div id="app">
	<! --> < span style = "box-sizing: border-box;
    <p v-for="(value,key,index) in obj" :key="key">Key name: {{key}}, value: {{value}}, index value: {{index}}</p>

    <! --> < span style = "max-width: 100%;
    <p v-for="item in 10" :key="item">{{ item }}</p>

    <! -- 5, traversal character -->
    <p v-for="item in 'chengshiliu'" :key="item">{{ item }}</p>
</div>

<script>
    var vm = new Vue({
        el: '#app',
        data: {
            obj: {
                    id: 1,
                    name: 'chengshiliu',
                    age: 17}}});</script>
Copy the code

conclusion

In this chapter, we mainly learned some built-in commands in VUE, familiar with their use method, all the source code of this article is provided at the beginning of the article warehouse address, each file description, you can check github warehouse readme description, hope you can pay more attention to it.

Of the pit

Personal Profile: Born in 1996, born in a fourth-tier city in Anhui province, graduated from Top 10 million universities. .NET programmer, gunslinger, cat. It will begin in December 2016. NET programmer career, Microsoft. NET technology stalwart, aspired to be the cloud cat kid programming for Google the best. NET programmer. Personal blog: yuiter.com blog garden blog: www.cnblogs.com/danvic712