Vue Select All and Select None

HTML code:

<script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script>
<div id="app">
    <p>
        全选:
    </p>
    <input type="checkbox" id="checkbox" v-model="checked" @change="changeAllChecked()">
    <label for="checkbox">
        {{checked}}
    </label>
    <p>
        多个复选框:
    </p>
    <input type="checkbox" id="runoob" value="Runoob" v-model="checkedNames">
    <label for="runoob">
        Runoob
    </label>
    <input type="checkbox" id="google" value="Google" v-model="checkedNames">
    <label for="google">
        Google
    </label>
    <input type="checkbox" id="taobao" value="Taobao" v-model="checkedNames">
    <label for="taobao">
        taobao
    </label>
    <br>
    <span>
        选择的值为:{{checkedNames}}
    </span>
</div>

Vue Code:

new Vue({
    el: '#app',
    data: {
        checked: false,
        checkedNames: [],
        checkedArr: ["Runoob", "Taobao", "Google"]
    },
    methods: {
        changeAllChecked: function() {
            if (this.checked) {
                this.checkedNames = this.checkedArr
            } else { this.checkedNames = []
            }
        }
    },
    watch: {
        "checkedNames": function() {
            if (this.checkedNames.length == this.checkedArr.length) {
                this.checked = true
            } else {
                this.checked = false
            }
        }
    }
})

Reference address code is: https://c.runoob.com/codedemo/3870  there effect

  This piece of code inside the most difficult to understand is why would the whole election, mainly because checkedArr inside the top box has a predefined value which, if checked is true of the time, the value checkedArr gave checkedNames, and then top box and CheckedNames relationship is bound, when the inside of the box inside the data values ​​above a value which values ​​are the same time, it is automatically selected. If you do not believe, then you can change it to a value above the value of the check boxes inside, and not just inside the array corresponding to the following, it will not selected.

  The following action is necessary to watch the monitor data: as used herein is the time value is changed and listening checkedNames not checked and the same length. If it means the whole length of the same election,

 

Guess you like

Origin www.cnblogs.com/xdtg/p/11902117.html