Vue quick use

Vue quick use

I. template syntax

1. Interpolation syntax

Syntax:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>interpolation</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>

<div id="box">
    <ul>
        <li>character string:{{name}}</li>
        <li>Value:{{age}}</li>
        <li>Array:{{list1}}</li>
        <li>Object:{{obj1}}</li>
        <li>character string:{{link1}}</li>
        <li>Operation:{{10+20+30+40}}</li>
        <li>Ternary operator:{{10>20?'yes':'no'}}</li>
    </ul>
</div>

</body>
<script>
    let vm = new Vue({
        el: '#Box ', / / the syntax of vue can be written in box div
        data: {
            name: 'Darker', // character string
            age: 18, // numerical value
            list1: [1,2,3,4],   // array
            obj1: {name: 'Darker', age: 19}, // object
            link1: '<a href="https://www.baidu. Com "> Baidu, you will know < / a > '
        }
    })
</script>
</html>

Second instruction

1. Text instruction

instructions interpretation
v-html Render HTML as a page
v-text The tag content displays the value corresponding to the js variable
v-show Put a Boolean value: if it is true, the label will be displayed; If the label is false, it will not be displayed
v-if Put a Boolean value: if it is true, the label will be displayed; If the label is false, it will not be displayed

The difference between v-show and v-if:

v-show: the tag is still there, but it is not displayed (display: none)
v-if: directly operate DOM, delete / insert Tags

v-html: make HTML render into pages

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>v-html</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>

<div id="box">
    <ul>
        <li v-html="link1"></li>
    </ul>
</div>

</body>
<script>
    let vm = new Vue({
        el: '#Box ', / / the syntax of vue can be written in box div
        data: {
            link1: '<a href="https://www.baidu. Com "> Baidu, you will know < / a > '
        }
    })
</script>
</html>

v-text: the tag content displays the value corresponding to the js variable

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>v-text</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>

<div id="box">
    <ul>
        <li v-text="link1"></li>
    </ul>
</div>

</body>
<script>
    let vm = new Vue({
        el: '#Box ', / / the syntax of vue can be written in box div
        data: {
            link1: '<a href="https://www.baidu. Com "> Baidu, you will know < / a > ',
        }
    })
</script>
</html>

v-show: Show / hide content

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>v-show</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>

<div id="box">
    <h3>Case: the control controls the display and display through buttons</h3>
    <button @click="handleClick()">Point me</button>
    <br>
    <div v-show="isShow">isShow</div>
</div>

</body>
<script>
    let vm = new Vue({
        el: '#box',
        data: {
            isShow: true,
        },
        methods: {
            handleClick(){
              this.isShow = !this.isShow    // this refers to the current vue object
            },
        }
    })
</script>
</html>

v-if: display / delete content

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>v-if</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>

<div id="box">
    <h3>Case: the control controls the display and disappearance through buttons</h3>
    <button @click="handleClick()">Point me</button>
    <br>
    <div v-if="isCreated">isCreated</div>
</div>

</body>
<script>
    let vm = new Vue({
        el: '#box',
        data: {
            isCreated:true
        },
        methods: {
            handleClick(){
              this.isCreated = !this.isCreated    // this refers to the current vue object
            },
        }
    })
</script>
</html>

2. Event instruction

instructions interpretation
v-on Trigger event (not recommended)
@ Trigger event (recommended)
@[event] Trigger event (can be any other event) event)

v-on:click can be abbreviated to @ click

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Event instruction</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>

<div id="box">
    <button v-on:click="handleClick1">Point me 1</button>
    <!-- The following one is more useful -->
    <button @click="handleClick2">Me at 2:00</button>
    <!-- If you do not pass parameters, there is no difference -->
    <button @click="handleClick3()">Point me 3-1(Parenthesized)</button>
    <!-- If you want to transfer parameters -->
    <button @click="handleClick3(1,22,333)">Point me 3-2(Parenthesized+parameter)</button>
    <!-- Incoming event -->
    <button @click="handleClick4($event)">Point me 4(With event parameters)</button>
</div>

</body>
<script>
    let vm = new Vue({
        el: '#box',
        data: {

        },
        methods: {
            handleClick1() {
                console.log('Point me 1')
            },
            handleClick2() {
                console.log('Me at 2:00')
            },
            handleClick3(a,b,c) {
                console.log(a,b,c)
            },
            handleClick4(event) {
                console.log(event)
            },
        }
    })
</script>
</html>

3. Attribute instruction

instructions interpretation
v-bind Write js variables or syntax directly (not recommended)
: Write js variables or syntax directly (recommended)

v-bind:class = 'js variable' can be abbreviated as: class = 'js variable'

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Attribute instruction</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
    <style>
        .red {
            color: rgba(255, 104, 104, 0.7);
        }
        .purple {
            color: rgba(104, 104, 255, 0.7);
        }
    </style>
</head>
<body>

<div id="box">
    <img v-bind:src="url" alt="" height="100">
    <br>
    <button @click="handleClick">Make me change color</button>
    <div :class="isActive?'red':'purple'">
        <h1>I am a div</h1>
    </div>
</div>

</body>
<script>
    let vm = new Vue({
        el: '#box',
        data: {
            url: 'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=205441424,1768829584&fm=26&gp=0.jpg',
            change: 'red',
            isActive: true
        },
        methods: {
            handleClick() {
                this.isActive = !this.isActive
            },
        }
    })
</script>
</html>

III. Style and Class

Data binding

grammar

: attribute name = js variable / js syntax

  • : class = "js variable, string, js array"

class: ternary operator, array, object {red: true}

  • : style = "js variable, string, js array"

style: ternary operator, array [{background: 'red'},], object {background: 'red'}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Style and Class</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
    <style>
        .red {
            color: rgba(255, 104, 104, 0.7);
        }
        .font-20 {
            font-size: 20px;
        }
        .be-bold {
            font-weight: bold;
        }
    </style>
</head>
<body>

<div id="box">
    <p>I am an ordinary person p label</p>
    <div :class="class_obj">
        <p>I am an unusual person p Label 1</p>
    </div>

    <button @click="handleClick">Click to enlarge the font</button>
    <div :style="style_obj">
        <p>I am an unusual person p Label 2</p>
    </div>
</div>

</body>
<script>
    let vm = new Vue({
        el: '#box',
        data: {
            // class_obj: 'red', / / put 1 as a string
            class_obj: ['red', 'font-20', 'be-bold'],    // Two are arrays
            // class_ Obj: {Red: true, be bold: false}, / / objects can also be placed
            // Array push() adds an element from the tail
            // Array pop() deletes the last element and returns

            // Object writing
            style_obj: {
                color: 'red',
                fontSize: '20px'
            }
            // style_obj: [{background:'red'}, {fontSize:'20px'}]

        },
        methods: {
            handleClick(){
                this.style_obj['fontSize']='30px'
            }
        }

    })
</script>
</html>
Command for test below
vm.class_obj.pop()
vm.class_obj.pop()
vm.class_obj.pop()
vm.class_obj.push('be-bold')
vm.class_obj.push('red')
vm.class_obj.push('font-20')

Four conditional rendering

instructions interpretation
v-if Equivalent to: if
v-else Equivalent to: else
v-else-if Equivalent to: else if
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>if,else if,else</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="box">
    <h3>Case: if,else if,else</h3>
    <h2 v-if="type==='1'">A</h2>
    <h2 v-else-if="type==='2'">B</h2>
    <h2 v-else>C</h2>
</div>
</body>
<script>
    let vm = new Vue({
        el: '#box',
        data: {
            type: '1',
        }
    })
</script>
</html>

Five list rendering

1. v-if+v-for+v-else controls the display of goods in shopping cart

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>v-if + v-for + v-else Control the display of shopping cart items</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
    <style>
        table, td {
            border: 1px solid black;
            text-align: center;
        }
    </style>
</head>
<body>
<div id="box">
    <h2>My shopping cart</h2>
    <button @click="show">Refresh shopping cart</button>
    <br><br>
    <table v-if="!shopping_car.length==0">
        <tr>
            <td>Trade name</td>
            <td>Price</td>
        </tr>
        <tr v-for="item in shopping_car">
            <td>{{item.name}}</td>
            <td>{{item.price}}</td>
        </tr>
    </table>
    <table v-else>
        <tr>
            <td>Trade name</td>
            <td>Price</td>
        </tr>
        <tr>
            <td>No information</td>
            <td>No information</td>
        </tr>
    </table>
</div>
</body>
<script>
    let vm = new Vue({
        el: '#box',
        data: {
            isActive: false,
            shopping_car: []
        },
        methods: {
            show() {
                this.shopping_car = [
                    {name: 'Threadripper 3990X', price: '29999 element'},
                    {name: 'NVIDIA RTX 8000', price: '59999 element'},
                    {name: 'ROG ZENITH II EXTREME', price: '9999 element'},
                ]
            }
        }
    })
</script>
</html>

2. v-for traverses arrays (lists), objects (dictionaries), and numbers

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>v-for Traversal array(list),object(Dictionaries)</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
    <style>
        table, td {
            border: 1px solid black;
            text-align: center;
        }
    </style>
</head>
<body>

<div id="box">
    <h2>Array (list) for Loop traversal</h2>
    <ul>
        <li v-for="(value,index) in list_test">{{index}} - {{value}}</li>
    </ul>

    <h2>Object (Dictionary) for Loop traversal</h2>
    <ul>
        <li v-for="(value,key) in dic_test">{{key}} - {{value}}</li>
    </ul>

    <h2>Array (list) set of objects (Dictionary) for Loop traversal</h2>
    <table>
        <tr>
            <td>full name</td>
            <td>Age</td>
            <td>Gender</td>
            <td>nationality</td>
        </tr>
        <tr v-for="info in summary_test">
            <td>{{info.name}}</td>
            <td>{{info.age}}</td>
            <td>{{info.gender}}</td>
            <td>{{info.country}}</td>
        </tr>
    </table>
</div>
</body>
<script>
    let vm = new Vue({
        el: '#box',
        data: {
            list_test: ['First', 'second', 'Third', 'Forth', 'Fifth'],
            dic_test:{name: 'Darker', age: 18, gender: 'male'},
            summary_test: [
                    {name: 'Alan', age: 23, gender: 'male', country: 'America'},
                    {name: 'Ben', age: 15, gender: 'male', country: 'Australia'},
                    {name: 'Cindy', age: 12, gender: 'female', country: 'Japan'},
                    {name: 'Darker', age: 18, gender: 'male', country: 'China'},
                    {name: 'Elisa', age: 26, gender: 'female', country: 'Mexico'},
                ]
        }
    })
</script>
</html>

be careful! In Vue:

  • The index and value of the array are opposite
  • The key and value of the object are also opposite

3. Explanation of key value

Virtual DOM is used in vue, which will be compared with the original DOM, and then the data will be updated to improve the refresh speed of data (diff algorithm is used in virtual DOM)

  • When v-for circulates arrays and objects, it is recommended to write a key attribute in the control / component / tag, and the attribute value is unique
  • After the page is updated, the replacement (rendering) of DOM will be accelerated
  • : key = "variable"

4. Array update and detection

Array operations that can detect changes:

push: add the last position
pop: delete the last position
shift: the first position is deleted
unshift: add at the first position
Slice: slice
Sort: sort
Reverse: reverse

Array operation with no change detected:

filter(): filter
concat(): append another array
slice():
map():

reason:

The author rewrites the relevant methods (only some methods are rewritten, but another part is not rewritten)

resolvent:
// Method 1: update the array through the index value (the data will be updated, but the page will not change)
vm.arrayList[0]
"Alan"
vm.arrayList[0]='Darker'
"Darker"

// Method 2: via Vue Set (object, index/key, value) updates the array (the data will be updated and the page will change)
Vue.set(vm.arrayList, 0, 'Darker')

Vi. event handling

event interpretation
input Event triggered when input is made in the input box
change Event triggered when the value of an element changes
blur Event triggered when the input box loses focus

The most essential difference between change and blur:

If the input box is empty, change will not trigger after losing focus, but blur will trigger

1. Filter cases

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Filter case</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="box">
    <p><input type="text" v-model="myText" @input="handleInput" placeholder="Please enter what to filter:"></p>
<!-- <p><input type="text" v-model="myText" @change="handleInput" placeholder="Please enter what to filter:"></p> -->
<!-- <p><input type="text" v-model="myText" @blur="handleInput" placeholder="Please enter what to filter:"></p> -->
    <ul>
        <li v-for="data in newList">{{data}}</li>
    </ul>
</div>
</body>
<script>
    var vm = new Vue({
        el: '#box',
        data: {
            myText: '',
            dataList: ['a', 'at', 'atom', 'be', 'beyond', 'cs', 'csrf'],
            newList: ['a', 'at', 'atom', 'be', 'beyond', 'cs', 'csrf'],
        },
        methods: {
            handleInput() {
                this.newList = this.dataList.filter(item => {
                    // item.indexOf(this.myText): the index of the string entered in the input box in the filter element
                    return item.indexOf(this.myText) > -1   // Return elements with an index greater than 1: > - 1 means included
                })
            },
        },
    })
</script>
</html>

2. Event modifier

Event modifier interpretation
.stop Only handle its own events, and the events bubbling from the parent control are not handled (prevent event bubbling)
.self Only handle its own events, and events with bubbling child controls are not handled
.prevent Block a link jump
.once Event can only be triggered once (applicable to lottery page)

When using modifiers, order is important; The corresponding code will be generated in the same order

Use v-on: click prevent. Self will block all clicks
And v-on: click self. Prevent only blocks clicks on the element itself

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Event modifier</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="box">
<!--    <ul @click="handleUl">-->
    <ul @click.self="handleUl">
<!--        <li v-for="data in dataList" @click="handleLi">{{data}}</li>-->
        <li v-for="data in dataList" @click.stop="handleLi">{{data}}</li>
        <li><a href="http://www.baidu. Com "> no interception</a></li>
        <li><a href="http://www.baidu. Com "@ Click =" handlelink ($event) "> Click to intercept</a></li>
        <li><a href="https://www.baidu. Com "@click.prevent =" handlelink "> Click to intercept</a></li>
        <li><button @click.once="test">Execute only once</button></li>
    </ul>
</div>
</body>
<script>
    var vm = new Vue({
        el: '#box',
        data: {
            dataList: ['1','22','333','4444']
        },
        methods: {
            handleUl(ev){
                console.log('ul It was clicked')
            },
            handleLi(){
                console.log('li It was clicked')
                ev.stopPropagation()    // Click event to stop bubbling (pass time to parent component)
            },
            handleLink(ev){
                ev.preventDefault()
            },
            test(){
                alert('Only triggered once')
            }
        }
    })
</script>
</html>

Event Bubbling

Prevent event bubbling

Block link jump + execute only once

3. Key modifier

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Key modifier</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="box">
    <!--    <input type="text" v-model="myInput" @keyup="handleKey">-->
    <!--    <input type="text" v-model="myInput" @keyup.13="handleKey">-->
    <input type="text" @keyup="handleKey1">
    <input type="text" @keyup.enter="handleKey2">
</div>
</body>
<script>
    var vm = new Vue({
        el: '#box',
        data: {
            dataList: ['1', '22', '333', '4444']
        },
        methods: {
            handleKey1(ev) {
                console.log('Pressed' + ev)
                // if (ev.keyCode==13){
                //     console.log('enter key pressed ')
                // }
            },
            handleKey2(ev) {
                console.log('Press enter')
            }
        }
    })
</script>
</html>

VII. Bidirectional data binding

Use of v-model

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="box">
    <input type="text" v-model="myText" placeholder="Please enter the content">
    The content you entered is:{{myText}}
</div>
</body>
<script>
    var vm = new Vue({
        el: '#box',
        data: {
            myText: '',
        },
    })
</script>
</html>

VIII. Form control

1. Check box

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>checkbox</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="box">
    <input type="text" placeholder="Please enter user name:"><br>
    <input type="password" placeholder="Please input a password:"><br>
    <input type="checkbox" v-model="radio">Remember user name
</div>
</body>
<script>
    var vm = new Vue({
        el: '#box',
        data: {
            myText: '',
            textBig: '',
            radio: false,
        },
    })
</script>
</html>

2. Single choice

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Single choice</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="box">
    <input type="radio" v-model="radio" value="male">male
    <input type="radio" v-model="radio" value="female">female
    <input type="radio" v-model="radio" value="secrecy">secrecy
    <br><br>Gender you selected:{{radio}}
</div>
</body>
<script>
    var vm = new Vue({
        el: '#box',
        data: {
            radio: '',
        },

    })
</script>
</html>

3. Multiple selection

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Multiple choice</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="box">

    <input type="checkbox" v-model="many" value="Basketball">Basketball
    <input type="checkbox" v-model="many" value="Football">Football
    <input type="checkbox" v-model="many" value="baseball">baseball
    <input type="checkbox" v-model="many" value="Table tennis">Table tennis
    <br><br>Your favorite balls:{{many}}
</div>
</body>
<script>
    var vm = new Vue({
        el: '#box',
        data: {
            many: [],
        },
    })
</script>
</html>

4. Shopping cart case - settlement

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Shopping cart settlement</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
    <style>
        table, td {
            border: 1px solid black;
            text-align: center;
        }
    </style>
</head>
<body>
<div id="box">
    <table>
        <tr>
            <td>Trade name</td>
            <td>Price</td>
            <td>quantity</td>
            <td>choice</td>
        </tr>
        <tr v-for="item in dataList">
            <td>{{item.name}}</td>
            <td>{{item.price}}</td>
            <td>{{item.number}}</td>
            <td><input type="checkbox" :value="item" v-model="checkGroup"></td>
        </tr>
    </table>
    <br>Selected items:{{checkGroup}}
    <br>Total price:{{getPrice()}}
</div>
</body>
<script>
    var vm = new Vue({
        el: '#box',
        data: {
            dataList: [
                {name: 'Not this bottle', price: 99, number: 2},
                {name: 'Grapefruit', price: 59, number: 1},
                {name: 'Kettle turn', price: 89, number: 5},
            ],
            checkGroup: [],
        },
        methods: {
            getPrice() {
                let sum_price = 0
                for (i in this.checkGroup) {    // i here is the index
                    sum_price += this.checkGroup[i]['number'] * this.checkGroup[i]['price']
                }
                return sum_price
            }
        }
    })
</script>
</html>

5. Shopping cart case - select all / none

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Select all/Not at all</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
    <style>
        table, td {
            border: 1px solid black;
            text-align: center;
        }
    </style>
</head>
<body>
<div id="box">
    <table>
        <tr>
            <td>Trade name</td>
            <td>Price</td>
            <td>quantity</td>
            <td>Select all/Not at all<input type="checkbox" v-model="allChecked" @change="checkAll"></td>
        </tr>
        <tr v-for="item in dataList">
            <td>{{item.name}}</td>
            <td>{{item.price}}</td>
            <td>{{item.number}}</td>
            <td><input type="checkbox" :value="item" v-model="checkGroup" @change="checkOne"></td>
        </tr>
    </table>
    <br>Selected items:{{checkGroup}}
    <br>Total price:{{getPrice()}}
</div>
</body>
<script>
    var vm = new Vue({
        el: '#box',
        data: {
            dataList: [
                {name: 'Not this bottle', price: 99, number: 2},
                {name: 'Grapefruit', price: 59, number: 1},
                {name: 'Kettle turn', price: 89, number: 5},
            ],
            checkGroup: [],
            allChecked: false,
        },
        methods: {
            getPrice() {
                let sum_price = 0
                for (i in this.checkGroup) {    // i here is the index
                    sum_price += this.checkGroup[i]['number'] * this.checkGroup[i]['price']
                }
                return sum_price
            },
            checkAll() {
                if (this.checkGroup.length > 0) {
                    this.checkGroup = []
                } else {
                    this.checkGroup = this.dataList
                }
            },
            checkOne() {
                // if (this.checkGroup.length === this.dataList.length) {
                //     this.allChecked = true
                // } else {
                //     this.allChecked = false
                // }
                this.allChecked = this.checkGroup.length === this.dataList.length;
            }
        }
    })
</script>
</html>

6. Shopping cart case - quantity addition and subtraction

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Control addition and subtraction</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
    <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="row">
    <div id="box" class="col-md-4 offset-md-1 text-center mt-5 ">
        <table class="table table-bordered">
            <thead>
            <tr>
                <th scope="col">Trade name</th>
                <th scope="col">Unit Price</th>
                <th scope="col">quantity</th>
                <th scope="col">Select all/Not at all <input type="checkbox" v-model="allChecked" @change="checkAll"></th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="item in dataList">
                <td>{{item.name}}</td>
                <td>{{item.price}}</td>
                <td>
                    <button class="btn link btn-sm" @click="reduceNum(item)">-</button>
                    {{item.number}}
                    <button class="btn link btn-sm" @click="item.number++">+</button>
                </td>
                <td><input type="checkbox" :value="item" v-model="checkGroup" @change="checkOne"></td>
            </tr>
            <tr class="text-left">
                <td colspan="4">Total price:{{getPrice()}}
            </tr>
            </tbody>
        </table>
    </div>
</div>
</body>
<script>
    var vm = new Vue({
        el: '#box',
        data: {
            dataList: [
                {name: 'Not this bottle', price: 99, number: 1},
                {name: 'Grapefruit', price: 59, number: 1},
                {name: 'Kettle turn', price: 89, number: 1},
            ],
            checkGroup: [],
            allChecked: false,
        },
        methods: {
            getPrice() {
                let sum_price = 0
                for (i in this.checkGroup) {
                    sum_price += this.checkGroup[i]['number'] * this.checkGroup[i]['price']
                }
                return sum_price
            },
            checkAll() {
                if (this.checkGroup.length > 0) {
                    this.checkGroup = []
                } else {
                    this.checkGroup = this.dataList
                }
            },
            checkOne() {
                // if (this.checkGroup.length === this.dataList.length) {
                //     this.allChecked = true
                // } else {
                //     this.allChecked = false
                // }
                this.allChecked = this.checkGroup.length === this.dataList.length;
            },
            reduceNum(item) {
                if (item.number === 1) {
                    item.number = 1
                } else {
                    item.number--
                }
            }
        }
    })
</script>
</html>

Nine v-model advanced

lazy, number, trim of v-model

lazy: wait for the data binding time zone focus of the input box before changing
Number: starts with a number, only numbers are reserved, and the following letters are not reserved; The beginning of the letter is reserved
trim: remove the first space

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>v-model of lazy,number,trim</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.12/vue.min.js"></script>
</head>
<body>
<div id="box">
    <input type="text" v-model="myText1" placeholder="normal"> {{myText1}}
    <br>
    <input type="text" v-model.lazy="myText2" placeholder="lazy"> {{myText2}}
    <br>
    <input type="text" v-model.number="myText3" placeholder="number"> {{myText3}}
    <br>
    <input type="text" v-model.trim="myText4" placeholder="trim"> {{myText4}}
</div>
</body>
<script>
    var vm = new Vue({
        el: '#box',
        data: {
            myText1: '',
            myText2: '',
            myText3: '',
            myText4: '',
        },
    })
</script>
</html>

Posted by mckooter on Sun, 15 May 2022 08:27:03 +0300