I see a lot of questions on Stack Overflow dealing with Vue JS and selecting a default single value from an Array. I, however, need to compare each item's array groups
to an array of ALL THE GROUPS ensemble_groups
, and load the correct selections by default.
Here's how I'm trying to do this now:
<div id="oven">
<template v-for="biscuit in oven">
<!--show checkbox for every available group-->
<!--check groups array to see if this ensemble_group should be selected by default-->
{{ ensemble_groups }}
<input type="checkbox"
name="cast_list[@{{ $index }}][groups][]"
:checked="biscuit.groups.IndexOf(name) == {{ group_name }}"
value="{{ group_name }}"
id="g-@{{ $index }}-{{ group_name|slugify }}">
<label for="g-@{{ $index }}-{{ group_name|slugify }}">{{ group_name }}</label>
<br>
{{ /ensemble_groups }}
</template>
</div>
So I've got my ALL THE GROUPS values stored in YAML as ensemble_groups.group_name
which match up to predefined values stored in YAML as cast_list.groups.value
and my Vue.js array is storing them as oven.groups.name
like so:
new Vue({
el: '#oven',
data: {
oven: [
{{ cast_list }}
{
groups: [
{{ groups }}
{
name: "{{ value }}"
},
{{ /groups }}
],
},
{{ /cast_list }}
]
}
})
Am I even making sense? I'm comparing the arrays (multiple predefined vs. all available).
So if I have 4 ensemble_groups values like ["Ballroom dancers", "Tap dancers", "Farmers", "Cowboys"]
and a cast_list entry is put into two groups ["Tap dancers", "Cowboys"]
, I want the checkboxes for those two groups to be checked when the page loads.
Help?
UPDATE:
I've used Roy's Answer to get the checkboxes working, but I've lost the index value to keep the data in the right place. Continued over at How to set incremental counter for nested arrays using Vue JS
Multiple checkboxes can be bound to an array to work the way you want. The snippet below lists the ensemble_groups
with checkboxes beside them. Below that, the cast_groups
array is listed. The cast_groups
array starts out with one value, but a timer programmatically adds one, then removes the first one so you can see it responding to data changes. You can also click the checkboxes to toggle membership, and the cast_groups
will be changed accordingly.
const v = new Vue({
el: 'body',
data: {
ensemble_groups: ["Ballroom dancers", "Tap dancers", "Farmers", "Cowboys"],
cast_groups: ['Tap dancers']
}
});
setTimeout(() => {
v.cast_groups.push('Farmers');
}, 2000);
setTimeout(() => {
v.cast_groups.$remove('Tap dancers');
}, 3500);
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/1.0.26/vue.min.js"></script>
<div v-for="group in ensemble_groups">
<input type="checkbox" value="{{group}}" v-model="cast_groups">{{group}}
</div>
<ul>
<li v-for="group in cast_groups">{{group}}</li>
</ul>