Basic use of vue

Table of contents

The front and back ends are separated, which can reduce the pressure on the server. Statically placed on the web server and dynamically placed on other servers

1. Template syntax

1.1 Interpolation

1.1.1 Text

1.1.2 html

1.1.3 Properties

1.1.4 Expressions

1.2 Instructions

1.2.1 Core Instructions

​edit

2. Filters

2.1 Local filters

2.2 Global Filters

3. Computed properties

4. Monitor properties

The front and back ends are separated, which can reduce the pressure on the server
static on the web server
Dynamically placed on other servers

1. Template syntax

First, define a msg in div, then use el in Vue to get an id and assign it in data (model)

Vue.js uses an HTML-based template syntax that allows developers to declaratively bind the DOM to the underlying Vue instance's data. All Vue.js templates are legal HTML, so they can be parsed by spec-compliant browsers and HTML parsers. vue compiles templates into virtual dom,
Combined with the reactivity system, Vue can intelligently calculate the minimum number of components to re-render and minimize the number of DOM manipulations.

html template syntax:
This is a string-based templating technique that takes a string and data as input and constructs a complete HTML string by replacing placeholders with the required data with regular expressions.

1.1 Interpolation

1.1.1 Text

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

<h1>{{msg}}</h1>

	msg: 'hello',

1.1.2 html

The method of {{}} processes the data into ordinary text. If you want to output html, you need to use the v-html instruction
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>

1.1.3 Properties

Values ​​in HTML attributes should use the v-bind directive. Type is the same as $("#xxx").attr(propName, propVal) in jQuery
For example, to modify the class attribute of an element as an example:
define a style

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

Define a property 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

1.1.4 Expressions

Several common expressions:

  • {{str.substr(0,6).toUpperCase()}}
  • {{ number + 1 }}
  • {{ ok ? 'YES' : 'NO' }} ternary operator
  • <li v-bind:>My Id is dynamically generated by js</li>

Example 1:

<!-- substring(0,6) to intercept characters 1-6 -->
<!-- toLocaleUpperCase() one-click capitalization -->


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'
}

Check 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 incremented by 1

Example 3:
This is a ternary operation, if ok is true, the expression value is YES, if ok is false then the expression value is NO

<!-- Remember to add '' -->

<span>{{ ok ? 'YES' : 'NO' }}</span>

Add an attribute to data named str corresponding to html

data: {
    ok: true
}

Example 4:
Demonstrate id property binding and dynamic assignment

<!-- This id cannot be seen directly on the web page, you can view it through the elements of the console -->

<p>
    <input type="text" v-bind:id="bookId"/></br>
    <!--Dynamic generation Id-->
    <input type="text" v-bind:id="'bookList_' + id"/>
</p>
data: {
    bookId: 'book001',
    id: 'book002'
}

The example can view the generated id attribute value through developer tools.

1.2 Instructions

Directives refer to special attributes prefixed with "v-"

1.2.1 Core Instructions

1.2.1.1 v-if |v-else-if|v-else

Whether or not to render the element depends on the bool value of the expression following it, the value of the directive attribute is expected to be a single JavaScript expression (v-for is the exception, we'll talk about it later)
Example:
HTML

<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, == first converts the type and then compares, === first judges the type, 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 is false behind it will not be rendered, and css code will be added to such elements: style="display:none".
When the v-show expression is true, it will be displayed, otherwise it will not be displayed.
Note: Using v-show, although it is not displayed, it exists in the dom of the page, but the display property is none
Example: Add the following to the HTML

<div v-show="show === 'yes'">
    show == yes
</div>

Define the show property 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

Figure 2 item.id is the value of Figure 1, through this id for for, and then display by name

 

 

  • 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 command to output, 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 dropdown 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: {
        itmes:[
            {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 checkboxes to get user selections

Because the checkbox is not a label body (but a label). So use span, div. . . Label to wrap, it is recommended to use template wrapping

template:  

 

span:

 

this is wrong

this is right

How to check the selected radio box, you can price v-model="selected" in div, how to define selected[] in js

operation result:

 

<!--
Loop to generate a set of multi-select buttons, v-model pass vue The two-way binding of the user-selected item is saved to
 Defined selected in the group
-->
<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 selection</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 Parameters v-bind:href,v-on:click

Example:

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

<!--
Parameters: dynamic parameters.
attname need in data defined in,
Notice: attname all lowercase!!
-->
<div>
    <a v-bind:[attrname]="url">baidu</a>
    <button v-on:[evname]="clickme">click me</button>
</div>

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

var vm = new Vue({

    el: '#app',

    data: {

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

    methods: {
        clickme: function() {
            console.log("click on me");
        }
    }

});

1.2.1.6 Shorthand

Vue provides specific shorthands for the two most commonly used directives, v-bind and v-on

instructionshorthandExample
v-bind:xxx:xxxv-bind:href is abbreviated as :href
v-on:xxx@xxxv-on:click is abbreviated as @click

bind: 

on:

 

2. Filters

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 pipeline operations character "|"

2.1 Local filters

If the filter in the figure is written at the back, the code will be executed from top to bottom, so it should be defined at the top

Error: For not placed in vue

is defined above:

 

Definition of local filter:

var vm = new Vue({
    filters: {
        'filterName': function(value) {
            //filter implementation
        }
    }
});

Use of filters

<!--Use of double curly braces-->
{{ name | capitalize }}

<!--exist v-bind use in directives-->
<div v-bind:id="rawId | formatId"></div>
  • Note 1: The filter function accepts the value of the expression as the first parameter
  • Note 2: Filters can be connected in series
    {{ message | filterA | filterB }}
  • Note 3: Filters are JavaScript functions, so can accept 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 Filters

Copy in date.js (date format) and put it in the project js directory and import it in the page.
Define global filters

//global filter
Vue.filter('fmtDate',function(value) {
    return fmtDate(value, 'yyyy year MM moon dd day')
});

Use of filters

<div>
    <p>{{date | fmtDate}}</p>
</div>

3. Computed properties

Computed properties are used to quickly compute properties displayed in the View, these computations will be cached and updated only when needed
Usage scenario: When a property requires complex logical operations to obtain its value, you can use computed properties. Various complex logics can be completed in a computed property, including operations, method calls, etc., as long as a result is finally returned.
The format for declaring a computed property:

computed:{
   xxx:function(){

   }
}

Example: Calculate the total price of a book using a computed property
Define test data, and calculate attributes, calculate attributes to traverse book records, calculate total price

var vm = new Vue({

    el: '#app',

    data: {
        //Define test data
        books: [
            {name:'A Dream of Red Mansions', price:"120"},
            {name:'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 a new addition to ES6, which can declare block-scoped variables (local variables)
  • It is recommended to use let to declare variables

4. Monitor properties

Usage scenario: We can use the monitoring property watch to respond to data variables, which is useful when we need to perform asynchronous or expensive operations when data changes. Recall that you have done cascading selections from drop-down lists?

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>
    <!--Notice v-model two-way binding-->
    Meter:     <input type="text" v-model="m">
    centimeter:  <input type="text" v-model="cm">
</div>

Tags: Javascript Vue.js Front-end

Posted by logicsound on Sun, 18 Sep 2022 21:54:56 +0530