I have checkbox in form and I would like to use v-if directly to show/hide sections in accordance of selected checkbox values.
Is it possible or I should use watch: ?
I have checkbox in form and I would like to use v-if directly to show/hide sections in accordance of selected checkbox values.
Is it possible or I should use watch: ?
It is possible. I would recommend adding a data model to the checkbox that toggles true or false. Then that will allow you to toggle the appearance of content using v-if.
Example:
<template>
<input type="checkbox" v-model="showContent" value="triggerString" />
<p v-if="showContent === 'triggerString'">Lorem ipsum</p>
</template>
<script>
export default {
data() {
return {
showContent: false
}
}
}
</script>
Generally speaking, we try not to use watch when we don't have to.
Update: Using the JSFiddle you included, this is how you would do it with just v-if
<template>
<input type="checkbox"
v-model="section"
name="section"
value="Epiphone"
id="epiphone">
<label for="epiphone">Epiphone</label>
<section v-if="section.includes('Epiphone')">
<h1>Epiphone</h1>
</section>
</template>
<script>
export default {
data() {
return {
section: []
}
}
}
</script>
Since there is two way binding occurring on the section array you created, there is no need for an additional div object since the only tracking that will occur will be in the section object.
The key thing to remember about v-if is that it can take actual JS expressions in it and not just data values. So you can extract out the logic from your watch method and simply plug it in there.
Hope this answers your question!
<section v-if="section.includes('Epiphone')">