简体   繁体   中英

Showing checked checkboxes with Vue.js

I am very new to vue, just need to change some code to make it work, and havent played much with vue. Can you please help.

I have a form with multiple checkboxes, just need to display checked checkboxes from array.

 <script>
    const sites = {"BN-C":"Brisbane Central","ML-C":"Melbourne Central","AMB-C":"Amberley Central","PEA-C":"Pearce Central"};
    let enabledSites = [];
    let selectedSites = ["BN-C","ML-C"];

    Vue.component('site_assignment', {
        data() {
            return {
                sites: sites,
                enabledSites : [],
                selectedSites: selectedSites,
            }
        },
        template: `
            <div class="form-group">
                <div class="row form-group" v-for="(key,val) in sites">
                    <div class="col-sm-1"></div>
                     <div class="col-sm-1">
                        <label for="site_assignment" class="control-label">@{{ key }}</label>
                    </div>
                    <div class="col-sm-2">
                        <input type="checkbox" :id="val" :value="val" v-model="enabledSites" @change="check()" v-bind:checked="selected">
                    </div>
                </div>
            </div>`,
        methods:{
            check(){
                enabledSites = this.enabledSites;
            },
        },
        computed: {
            selected(){
                return true;
            }
        }
    });

    new Vue({
        el: '#site_assignment',
    })
</script>

I tried using v-bind but thats not working. My sites object is having all sites and the selectedSites have items which should get checked.

enabledSites gets updated when you check/uncheck items and this is then used by other script.

So BN-C and ML-C shoudl be checked.

 new Vue({ el: '#app', data: { sites: { "BN-C": "Brisbane Central", "ML-C": "Melbourne Central", "AMB-C": "Amberley Central", "PEA-C": "Pearce Central" }, enabledSites: ["BN-C", "ML-C"] }, methods: { check() { console.log(this.enabledSites); } } })
 <script src="https://unpkg.com/vue"></script> <div id="app"> <div class="form-group"> <div class="row form-group" v-for="(key,val) in sites" :key="key"> <div class="col-sm-1"></div> <div class="col-sm-1"> <label for="site_assignment" class="control-label">@{{ key }}</label> </div> <div class="col-sm-2"> <input type="checkbox" :id="val" :value="val" v-model="enabledSites" @change="check()"> </div> </div> </div> </div>

If are using v-model, checked wont work in the checkbox. You have to handle that manually. Here the link that might help you In Vue, v-binding is not working on the "checked" property for Bootstrap Toggle Checkboxes?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM