Vdue’s template syntax & instructions & filters & calculated attributes & listening attributes

Template syntax

Vue.js uses an HTML-based template syntax that allows developers to declaratively bind the DOM to the data of the underlying Vue instance. All Vue.js templates are legal HTML and can be parsed by browsers and HTML parsers that follow the specification. vue compiles the template into virtual dom,
Combined with the responsive system, Vue can intelligently calculate how many components need to be re-rendered and minimize the number of DOM operations.

html template syntax:

This is a string-based template technology that takes strings and data as input and builds a complete HTML string by replacing placeholders with the required data using regular expressions.

Interpolation

text
Using the form {{msg}}, the label will be replaced by the msg attribute value on the data object (data). When the msg attribute value on the bound data object changes, the interpolation The value will also change (two-way binding)
Example: The hello vue example in the previous lesson uses interpolation.

html
{{}} processes the data into ordinary text. If you want to output html, you need to use the v-html command.
Example:
Define an html attribute in data whose value is html

data: {<!-- -->
    html: '<input type="text" value="hello"/>'
}

Get value in html

<span v-html="html"></span>

Attributes
Values in HTML attributes should use the v-bind directive. The type is the same as $(“#xxx”).attr(propName, propVal) in jQuery
For example, take modifying the class attribute of an element as an example:
define a style

<style>
.redClass {<!-- -->
    font-size: 30px;
    color: red;
}
</style>

Define an attribute in data whose value is the style name defined above

data: {<!-- -->
    red: 'redClass'
}

Use v-bind directive to set styles in html

<p>Before setting: aaaa</p>
<p>After setting: <span v-bind:class="red">aaa</span></p>

You can see the corresponding effect in the browser
expression
Several common expressions:

  • {{str.substr(0,6).toUpperCase()}}
  • {{ number + 1 }}
  • {{ ok ? YES’ : NO’ }} ternary operator
  • My ID is dynamically generated by js

Example 1:

Add elements to html and define expressions

<span>{<!-- -->{<!-- -->str.substr(0,6).toUpperCase()}}</span>
Add an attribute to data named str corresponding to html

data: {<!-- -->
    str: 'hello vue'
}
View the effect: the string is intercepted and converted to uppercase

Example 2:

<span>{<!-- -->{<!-- --> number + 1 }}</span>
Add an attribute to data named str corresponding to html
data: {<!-- -->
    number: 10
}
The number value defined in data will be increased by 1

Example 3:

This is a ternary operation. If ok is true, the expression value is YES. If ok is false, the expression value is NO.

<span>{<!-- -->{<!-- --> ok ? 'YES' : 'NO' }}</span>
Add an attribute to data named str corresponding to html

data: {<!-- -->
    OK: true
}

Example 4:

Demonstrate id attribute binding and dynamic assignment

<p>
    <input type="text" v-bind:id="bookId"/></br>
    <!--Dynamically generate Id-->
    <input type="text" v-bind:id="'bookList_' + id"/>
</p>
data: {<!-- -->
    bookId: 'book001',
    id: 'book002'
}
This example can view the generated id attribute value through the developer tools.

instruction
Directives refer to special attributes prefixed with “v-“
1.2.1 Core instructions
1.2.1.1 v-if |v-else-if|v-else
Determine whether to render the element based on the bool value of the subsequent expression. The value of the directive attribute is expected to be a single JavaScript expression (v-for is an exception, we will discuss it later)
Example:

<div v-if="type === 'A'">
    type==A
</div>
<div v-else-if="type === 'B'">
    type==B
</div>
<div v-else>
    other value
</div>
JS

    var vm = new Vue({<!-- -->

        el: '#app',

        data: {<!-- -->
            type: 'C'
        }
    });

You can modify the type value in data to observe the output of the page.

Note: The difference between js = == ===
An equal sign is an assignment operation. == converts the type first and then compares. === determines the type first. If it is not the same type, it is directly false.
alert(1 == “1”); // true
alert(1 === “1”); // false

1.2.1.2 v-show
Similar to v-if, except that elements whose expression behind them is false will not be rendered, and CSS code will be added to such elements: style=”display:none”.
When the v-show expression is true, it is displayed, otherwise it is not displayed.
Note: Using v-show, although it is not displayed, it exists in the DOM of the page, but the display attribute is none.
Example: Add the following content to HTML

<div v-show="show === 'yes'">
    show == yes
</div>
Define the show attribute in data

var vm = new Vue({<!-- -->
    el: '#app',
    data: {<!-- -->
        show: 'yes'
    }
});

Modify the show value and observe the page display

1.2.1.3 v-for
Loop through

Traverse the array: v-for=”item in items”, items is the array, item is the array element in the array
Traverse objects: v-for=”(value,key,index) in stu”, value attribute value, key attribute name, index subscript
Example:

Define a div and use the v-for instruction to output it. items is an array of objects defined in data in the vue instance.
<!--Array-->
<div v-for="item in items">
     {<!-- -->{<!-- -->item.name}} -- {<!-- -->{<!-- -->item.id}}
</div>

<!--Loop to generate drop-down list-->
<div>
    <select>
        <option v-for="item in items"
            v-bind:value="item.id">{<!-- -->{<!-- -->item.name}}</option>
    </select>
</div>

<!--Object-->
<div v-for="(o,key) in obj">
    {<!-- -->{<!-- -->key}}-{<!-- -->{<!-- -->o}}
</div>
var vm = new Vue({<!-- -->

    el: '#app',

    data: {<!-- -->
        items:[
            {<!-- -->name: 'zs',age:18},
            {<!-- -->name: 'ww',age:19},
            {<!-- -->name: 'ls',age:20},
            {<!-- -->name: 'zl',age:21}
        ],
        obj: {<!-- -->
            name:'Zhang San',
            age: 21,
            addr: 'Changsha, Hunan'
        }
    }
});

1.2.1.4 v-on|v-model|v-for
Create a set of multi-select boxes to obtain user selections

<div v-for="(item,index) in items">
    {<!-- -->{<!-- -->index}}:<input type="checkbox" v-bind:value="item.id"
            v-model="selected">{<!-- -->{<!-- -->item.name}}
</div>
<button v-on:click="getSelected()">Get selected</button>
var vm = new Vue({<!-- -->

    el: '#app',

    data: {<!-- -->
        type: 'C',
        show: 'no',
        items:[
            {<!-- -->name: 'Changsha',id:18},
            {<!-- -->name: 'Kunming',id:19},
            {<!-- -->name: 'Wuhan',id:20},
            {<!-- -->name: 'Nanjing',id:21}
        ],
        obj: {<!-- -->
            name:'Zhang San',
            age: 21,
            addr: 'Changsha, Hunan'
        },
        selected:[]
    },
    methods: {<!-- -->
        getSelected: function() {<!-- -->
            console.log(this.selected);
        }
    }
});

1.2.1.5 Parameter v-bind:href,v-on:click
Example:

<!--Parameter: href-->
<div>
    <a v-bind:href="url">baidu</a>
</div>

<!--
Parameters: dynamic parameters.
attname needs to be defined in data,
Note: attname must be all lowercase!!
-->
<div>
    <a v-bind:[attrname]="url">baidu</a>
    <button v-on:[evname]="clickme">Click me to see</button>
</div>

Note: In dynamic parameters, the variable name used as a parameter (such as: attrname) must be all lowercase, otherwise it will be invalid! !

var vm = new Vue({<!-- -->

    el: '#app',

    data: {<!-- -->

        url: 'https://www.baidu.com',
        attrname:'href',
        evname: 'click'
    },

    methods: {<!-- -->
        clickme: function() {<!-- -->
            console.log("I was clicked");
        }
    }

});

1.2.1.6 Abbreviation
Vue provides specific abbreviations for the two most commonly used instructions, v-bind and v-on.

Command Abbreviation Example
v-bind:xxx :xxx v-bind:href is abbreviated as :href
v-on:xxx @xxx v-on:click abbreviated as @click
2. Filter
Vue allows custom filters, generally used for common text formatting. Filters are available in two places: double curly brace interpolation and v-bind expressions. Filters should be added at the end of js expressions, using pipe operations. Symbol “|”

2.1 Local filter
Definition of local filter:

var vm = new Vue({<!-- -->
    filters: {<!-- -->
        'filterName': function(value) {<!-- -->
            //Filter implementation
        }
    }
});
Use of filters

<!--Usage in double curly braces-->
{<!-- -->{<!-- --> name | capitalize }}

Note 1: The filter function accepts the value of the expression as the first parameter Note 2: Filters can be concatenated {{ message | filterA | filterB }} Note 3: Filters are JavaScript functions, so they can Accepts parameters: {{ message | filterA(‘arg1’, arg2) }} Example:

<div>
    <p>{<!-- -->{<!-- -->msg | toUpperCase}}</p>
</div>
var vm = new Vue({<!-- -->

    el: '#app',

    data: {<!-- -->
        msg:"hello vue"
    },

    //local filter
    filters:{<!-- -->
        toUpperCase: function(value) {<!-- -->
            return value.toUpperCase();
        }
    }

});

2.2 Global filter
Copy date.js (date formatting) into the project js directory and introduce it into the page.
Define global filters

//global filter

Vue.filter('fmtDate',function(value) {<!-- -->
    return fmtDate(value, 'yyyy year MM month dd day')
});

Use of filters

<div>
    <p>{<!-- -->{<!-- -->date | fmtDate}}</p>
</div>
  1. Computed properties
    Computed properties are used to quickly calculate the properties displayed in the view. These calculations will be cached and updated only when needed.
    Usage scenarios: When an attribute requires complex logical operations to obtain its value, you can use calculated attributes. Various complex logic can be completed in a calculated attribute, including operations, method calls, etc., as long as a result is returned in the end.
    The format for declaring computed properties:
computed:{<!-- -->
   xxx:function(){<!-- -->
 }
}

Example: Use calculated properties to calculate the total price of a book
Define test data and calculated attributes. The calculated attributes traverse the book records and calculate the total price.

var vm = new Vue({<!-- -->

    el: '#app',

    data: {<!-- -->
        //Define test data
        books: [
            {<!-- -->name:'A Dream of Red Mansions', price: "120"},
            {<!-- -->name:'Romance of the Three Kingdoms', price:"100"},
            {<!-- -->name:'Water Margin', price:"90"},
        ]
    },

    //Computed property
    computed: {<!-- -->
        compTotal: function() {<!-- -->
            let sum = 0;
            for(index in this.books) {<!-- -->
                sum + = parseInt(this.books[index].price);
            }
            return sum;
        }
    }

});

Use of computed properties in pages

<div v-for="book in books">
    {<!-- -->{<!-- -->book.name}} -> {<!-- -->{<!-- -->book.price}}
</div>

<div>
    Total price: {<!-- -->{<!-- -->compTotal}}
</div>

About var and let

var is declared as a global property
Let is new in ES6 and can declare block-level variables (local variables)
It is recommended to use let to declare variables
4. Monitoring attributes
Usage scenarios: We can use the monitoring attribute watch to respond to data variables. This method is more useful when we need to perform asynchronous or expensive operations when the data changes. Recall whether you have ever made cascading selections from a drop-down list?

watch declaration syntax:

watch: {<!-- -->
    xxxx: function(val) {<!-- -->
        //Listener implementation
    }
}

Example: Unit conversion between meters and centimeters
Set up the listener:

var vm = new Vue({<!-- -->

    el: '#app',

    data: {<!-- -->
        m: 1,
        cm: 100
    },

    //Set listening properties
    watch: {<!-- -->
        m: function(val) {<!-- -->
            if(val)
                this.cm = parseInt(val) * 100;
            else
                this.cm = "";
        },
        cm: function(val) {<!-- -->
            if(val)
                this.m = parseInt(val) / 100;
            else
                this.m = "";
        }
    }

});

Using v-model in HTML to achieve two-way binding with data

<div>
    <!--Note the two-way binding of v-model-->
    m: <input type="text" v-model="m">
    Centimeters: <input type="text" v-model="cm">
</div>