3, Detailed usage of v-model instruction, event modifier and key modifier

Posted by benwilhelm on Thu, 03 Feb 2022 13:12:32 +0100

① Detailed usage of v-model instruction

1.v-model instruction, bind the contents of text box to realize bidirectional data binding

<input type="text" v-model="name">

2.v-model instruction, bind the contents of multi line text box to realize two-way data binding

Note: interpolation in the text area (< textarea > {text}} < / textarea >) will not take effect, and v-model should be used instead.

<textarea cols="80" rows="4" v-model="address"></textarea>

3. Single check box, bind a Boolean value through v-model, select = > true, uncheck = > false

<input type="checkbox" v-model="isOK">

4. Multiple check boxes are bound to the same array through v-model

<input type="checkbox" value="Play basketball" v-model="hobbies">Play basketball
<input type="checkbox" value="play the piano" v-model="hobbies">play the piano
<input type="checkbox" value="sing" v-model="hobbies">sing

5. Multiple radio boxes bind the same attribute through v-model

<input type="radio" value="male" name="sex" v-model="sex">male
<input type="radio" value="female" name="sex" v-model="sex">female

6. You can bind an attribute to the drop-down box through v-model

<select v-model="education">
     <option value="primary school">primary school</option>
     <option value="master">master</option>
     <option value="doctor">doctor</option>
     <option value="post-doctoral">post-doctoral</option>
</select>

After setting the multiple attribute in the drop-down box, you can select multiple items. You can bind an array to the drop-down box through v-model

<select v-model="foods" multiple>
    <option value="Crab">Crab</option>
    <option value="lobster">lobster</option>
    <option value="drumsticks">drumsticks</option>
    <option value="steak">steak</option>
    <option value="seafood">seafood</option>
</select>

7.v-model instruction, adding The lazy Modifier updates the data after the text box loses focus

<input type="text" v-model.lazy="msg">

8. v-model instruction, adding number modifier. When modifying the content of the text box, the modified content will be converted to

number type

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

9.v-model instruction, adding trim modifier. When modifying the content of the text box, the spaces before and after will be ignored

<input type="text" v-model.trim="city">

② Event modifier

v-on: the instruction binds events. You can specify an event method. The event method should be defined in methods. appoint

If no parameters are passed to the event method, an event object parameter will be passed by default.

<button v-on:click="sayHi">Say Hi</button>

If we pass a parameter and want to pass the event object parameter again, we need to set it through the $event keyword.

<button v-on:click="sayHello('Hello',$event)">Say Hello</button>

If the logic of event processing is relatively simple, it can be written directly in the line.  

<button v-on:click="name+='*'">modify name</button>

1. Adoption prevent event modifier to block default behavior

2. Adoption stop event modifier to prevent event bubbling

<div class="a" @click="a" @contextmenu.prevent="cm">
     <div class="b" @click.stop="b"></div>
</div>

3. Adoption Once event modifier to make the event method execute only once

<button @click.once="once">Trigger only once</button>

4. Adoption self event modifier, which controls the event to be triggered on the current element itself and not on the internal element

<div class="c" @click.self="c">
    <div class="d"></div>
</div>

5. By default, the capture mode of the mobile phone is to execute one by one from the inside to the outside. If an external event is added

Add Capture modifier. At this time, the capture mode of events becomes, which is executed one by one from the outside to the inside.

<div class="e" @click.capture="e">
     <div class="f" @click="f"></div>
</div>

Note: modifiers can be concatenated. Summary: when using modifiers, order is important. Therefore, use v-on: click prevent. Self meeting

Block all clicks, and v-on: click self. Prevent only blocks clicks on the element itself.

③ Key modifier

Vue provides key modifiers for keyboard events. There are 9 key modifiers in total, which are:

. enter is the Enter key

. tab is the tab key

. delete is the delete key and backspace key

. esc is the exit key

. space is the space bar

. up is the up arrow

. down is the down arrow

. left is the left arrow

. right is the right arrow

Key modifier can also be replaced by key code. Note: key code is cancelled in Vue3

<input type="text" v-model="keywords" @keyup.13="keydown">

④ Depth response

Vue instances will respond to all data on the object during initialization,

Then add attributes to the object, and these attributes no longer have the ability to respond.

For arrays, only the following methods can be used to realize the response type:

push()   pop()    unshift()     shift()     splice()    reverse()     sort()

        <button @click="arr.push('cola')">Add coke at the end</button>
        <button @click="arr.pop()">Delete end element</button>
        <button @click="arr.unshift('pineapple')">Add pineapple at the beginning</button>
        <button @click="arr.shift()">Delete start element</button>
        <button @click="arr.splice(1,1,'Durian')">Modify elements by method</button>
        <button @click="arr.splice(1,2)">Delete element</button>
        <button @click="arr.reverse()">Array element inversion</button>
        <button @click="arr1.sort((a,b)=>a-b)">Element sorting</button>

How to solve the above problems?

Method 1: update the specified object attribute or array member through Vue's set method; The delete method deletes the attribute of the specified object or the member of the array

Method 2: update the specified object attribute or array member through the $set method of Vue instance$ The delete method deletes the attribute of the specified object or the member of the array

methods: {
                // Method for adding working properties to an object
                addJob() {
                    // Through observation, we can find that we can add attributes to the object, but the added attributes do not have the ability of responsiveness.
                    // this.obj.job = 'front end development engineer'
                    // The parameters of the set method are: the specified object, the attribute of the object, and the attribute value
                    // Vue.set(this.obj,'job', 'front end development engineer')
                    this.$set(this.obj, 'job', 'Front end development engineer')
                },
                // Method of deleting age on object
                delAge() {
                    // delete this.obj.age
                    // The parameters of the delete method are: the specified object and the attributes of the object
                    // Vue.delete(this.obj,'age')
                    this.$delete(this.obj, 'age')
                },
                // Modify the members of the array
                updateArr() {
                    // this.arr[1] = 'Apple'

                    // Here, the parameters of the set method are: the specified array, the subscript of the array, and the corresponding data
                    this.$set(this.arr, 1, 'Apple')
                },
                // Delete array elements according to Subscripts
                delArr() {
                    // delete this.arr[1]

                    // The parameters of the delete method here are: the specified array and the subscript of the array
                    this.$delete(this.arr, 3)
                }
            },

⑤ Shopping cart case

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Shopping Cart</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            list-style: none;
            text-decoration: none;
            outline: none;
        }

        #app {
            width: 700px;

        }

        table {
            border-collapse: collapse;
        }

        th,
        td {
            padding: 5px 10px;
            border: 1px solid #ccc;
        }

        img {
            width: 80px;
        }

        td .btn {
            padding: 5px 14px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
        }

        td .btn:hover {
            background-color: #ea13ad;
            color: white;
        }

        td .count {
            width: 50px;
            padding: 5px;
            text-align: center;
            border: none;
        }

        td .del {
            cursor: pointer;
            padding: 5px 10px;
            border: none;
            border-radius: 5px;
        }

        td .del:hover {
            background-color: #ea13ad;
            color: white;
        }
    </style>
</head>

<body>
    <div id="app">
        <!-- If there is data in the array, the shopping cart is displayed -->
        <table v-if="goodses.length>0">
            <tr>
                <th><input type="checkbox" v-model="isckAll" />Select all</th>
                <th>Trade name</th>
                <th>Product picture</th>
                <th>item pricing </th>
                <th>Purchase quantity</th>
                <th>Subtotal</th>
                <th>operation</th>
            </tr>
            <tr v-for="(item,index) in goodses" :key="item.id">
                <td><input type="checkbox" v-model="item.isck" /></td>
                <td>{{item.name}}</td>
                <td>
                    <img :src="item.img" />
                </td>
                <td>¥{{item.price | toFixed2}}</td>
                <td>
                    <!-- :disabled The bound value is true,Button disabled -->
                    <button @click="item.count--" :disabled="item.count===1" class="btn">-</button>
                    <input readonly type="text" :value="item.count" class="count" />
                    <button @click="item.count++" :disabled="item.count===10" class="btn">+</button>
                </td>
                <td>¥{{item.price*item.count | toFixed2}}</td>
                <td>
                    <button @click="delGoods(index)" class="del">delete</button>
                </td>
            </tr>
            <tr>
                <td colspan="7" class="totalPrice">
                    <span>total:¥{{totalPrice | toFixed2}}</span>
                    <!-- Filters can be called chained -->
                    <span style="color: red">${{totalPrice | toUS | toFixed2}}</span>
                </td>
            </tr>
        </table>
        <!-- Otherwise, the following is displayed div -->
        <div class="empty" v-else>Your shopping cart is empty</div>
    </div>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.14/vue.js"></script>
    <script>
        new Vue({
            el: "#app",
            // data
            data: {
                // Item array
                goodses: [
                    {
                        // Item number
                        id: "1001",
                        // Trade name
                        name: "Mi phones",
                        // Product picture
                        img: "https://img.alicdn.com/bao/uploaded/i3/2279837698/O1CN01gkdsUP26jjYlI8HCS_!!2279837698.jpg",
                        // item pricing 
                        price: 1999,
                        // Purchase quantity
                        count: 3,
                        // Check
                        isck: false,
                    },
                    {
                        id: "1002",
                        name: "Siemens refrigerator",
                        img: "https://img.alicdn.com/bao/uploaded/i4/2347095319/O1CN01xhxce31pA9MmYjHPc_!!2347095319.jpg",
                        price: 3999,
                        count: 2,
                        isck: true,
                    },
                    {
                        id: "1003",
                        name: "Sony TV",
                        img: "https://img.alicdn.com/bao/uploaded/i1/782731205/O1CN01o18KOx1KlvvaEIosx_!!0-item_pic.jpg",
                        price: 4999,
                        count: 1,
                        isck: true,
                    },
                    {
                        id: "1004",
                        name: "Lenovo computer",
                        img: "https://img.alicdn.com/bao/uploaded/i2/459462135/O1CN01yN7bD91RdsIyoddVW_!!459462135.jpg",
                        price: 5999,
                        count: 4,
                        isck: false,
                    },
                ],
            },
            // method
            methods: {
                delGoods(index) {
                    if (confirm("Are you sure to delete?")) {
                        this.goodses.splice(index, 1);
                    }
                },
            },
            // Calculation properties
            computed: {
                // Indicates whether to select all
                isckAll: {
                    // Return results
                    get() {
                        // Returns true when the status of all items in the item array is true
                        return (
                            this.goodses.length > 0 && this.goodses.every((g) => g.isck)
                        );
                    },
                    // Modification results
                    set(val) {
                        // Cycle all commodities and set the status of all commodities to the latest select all status
                        this.goodses.forEach((g) => {
                            g.isck = val;
                        });
                    },
                },
                // Represents the total price
                totalPrice() {
                    /* let total = 0
                                    for(let i=0;i<this.goodses.length;i++){
                                        if(this.goodses[i].isck){
                                            total += this.goodses[i].count * this.goodses[i].price
                                        }
                                    }
                                    return total */

                    let total = 0;
                    this.goodses.forEach((g) => {
                        if (g.isck) {
                            total += g.price * g.count;
                        }
                    });
                    return total;

                    /* return this.goodses.filter(g=>g.isck).map(g=>g.price*g.count).reduce((c,g)=>{
                                        return c + g
                                    },0) */
                },
            },
            // filter
            filters: {
                // The number retains two decimal places
                toFixed2(val) {
                    return val.toFixed(2);
                },
                // How to transfer to US dollars
                toUS(val) {
                    return val / 6.444;
                },
            },
            // monitor
            watch: {
                // Listen for changes in the value of the totalPrice calculation attribute
                totalPrice(val) {
                    if (val >= 10000) {
                        alert("Please consume rationally!");
                    }
                },
            },
        });
    </script>
</body>

</html>

Topics: Javascript Front-end Vue.js