I'm facing a few challenges as I dive into learning Vue.js for just one week. Keep in mind that this example is actually nested within a parent component called <question>
, but for the sake of simplicity, I've streamlined the code for this post.
- Is there a way to have certain items pre-checked when the page loads?
Edit — I cracked number 1. Just needed to use [ "Chicken", "Turkey", "Beef", "Fish", "Pork" ]
- How can I deselect specific items, like unchecking meat options if I choose Vegan?
- How do I add Exclude and Include checkboxes next to my options?
https://i.stack.imgur.com/GGOSe.gif
Checkbox
<div id="questionnaire">
<checkbox v-model="form.meats" id="8a" option="Chicken"></checkbox>
<checkbox v-model="form.meats" id="8b" option="Turkey"></checkbox>
<checkbox v-model="form.meats" id="8c" option="Beef"></checkbox>
<checkbox v-model="form.meats" id="8d" option="Pork"></checkbox>
<checkbox v-model="form.meats" id="8e" option="Fish"></checkbox>
<checkbox v-model="form.meats" id="8f" option="Vegetarian Only"></checkbox>
<checkbox v-model="form.meats" id="8g" option="Vegan Only"></checkbox>
{{ form.meats }}
</div>
Vue.component('checkbox')
Vue.component('checkbox', {
template: `
<div>
<input type="checkbox" :id="id" :value="option" v-model="checked" @change="update">
<label :for="id">
{{ option }}
<slot></slot>
</label>
</div>
`,
data() {
return {
checkedProxy: false
}
},
computed: {
checked: {
get() {
return this.value
},
set(option) {
this.checkedProxy = option
}
}
},
methods: {
update: function(e) {
this.$emit('input', this.checkedProxy)
}
},
props: {
value: null,
option: null,
id: {
type: String,
required: true
}
}
});
new Vue({
el: "#questionnaire",
data: {
form: {
meats: [],
}
}
})