I have a list of checkbox which is dynamic. Whenever I click on the checkbox, it is binded to the data array. The index is provided as the top company name. But the array shows empty when I log the array. But if I iterate through it and log again, it shows the values. In JS we cannot set the array index directly. Is that the problem? Code:
new Vue({
el: '#app',
data: {
topCompanies: [{
"doc_count": 221,
"key": "a"
},
{
"doc_count": 175,
"key": "b"
},
{
"doc_count": 149,
"key": "c"
},
{
"doc_count": 126,
"key": "d"
},
{
"doc_count": 116,
"key": "e"
},
{
"doc_count": 115,
"key": "f"
},
{
"doc_count": 94,
"key": "g"
},
{
"doc_count": 89,
"key": "h"
},
{
"doc_count": 75,
"key": "h"
},
{
"doc_count": 72,
"key": "i"
}
],
collapse1: false,
checked_company: []
},
methods: {
getResultsByCompany(result) {
console.log(this.checked_company)
temp = []
for (i in this.checked_company) {
console.log(i)
}
}
}
});
<div id="app">
<div id="sidebar-wrapper">
<button class="collapsible" @click="collapse1=!collapse1">Top Companies</button>
<div v-if="collapse1" class="content" v-bind:style="{'display': 'block'}">
<div class="list-group" v-for = "(result,index) in topCompanies" :key="result.id">
<label class="container check-an" :id="index" @change = "getResultsByCompany(result.key)">{{ result.key}}({{result.doc_count }})
<input type="checkbox" v-model="checked_company[result.key]">
<span class="checkmark"></span>
</label>
</div>
js fiddle: https://jsfiddle.net/Lbkx5zdt/
You declare checked_company
as an array, but you treat it as an object checked_company[result.key]
If you want to save all checked company key in an array, then your checkbox code should be
<input type="checkbox" :value="result.key" v-model="checked_company">
I see you seem missing several div tags
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
<div id="sidebar-wrapper">
<button class="collapsible" @click="collapse1=!collapse1">Top Companies</button>
<div v-if="collapse1" class="content" v-bind:style="{'display': 'block'}">
<div class="list-group" v-for = "(result,index) in topCompanies" :key="result.id">
<label class="container check-an" :id="index" @change = "getResultsByCompany(result.key)">{{ result.key}}({{result.doc_count }})
<input type="checkbox" v-model="checked_company[result.key]">
<span class="checkmark"></span>
</label>
</div>
</div>
</div>
</div>
It make vuejs don't know el scope
I'm not really sure this will be the issue but have you checked that 'this' refers to the correct object? Potentially you could assign a variable to new Vue and reference the object globally. Hope it helps.
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.