12

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: ?

4
  • What happens when you try it? Commented May 10, 2017 at 0:19
  • works until two or more is selected Commented May 10, 2017 at 0:58
  • @rpz There are many possible answers. Please post a small, concise code example so that we can help you find the right answer. Commented May 10, 2017 at 4:01
  • I created the fiddle with watch expression, any thoughts how to avoid watch: and do it directly in v-if? jsfiddle.net/w6svt1w7/5 Commented May 10, 2017 at 15:14

1 Answer 1

24

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!

Sign up to request clarification or add additional context in comments.

4 Comments

thank you. What if showContent is an array that has two values ['apple','orange]. Would it be possible to check with v-if that apple is in array? I am working with long forms and would like to cut the code as much as possible but at the same time I am newbie, much to learn..
@rpz Yes. You can use the indexOf property on the array to return true or false based on whether the index is greater than -1.
@rpz I've updated the answer with a sample from your JSFiddle
this helped me thank you <section v-if="section.includes('Epiphone')">

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.