1

In my Vue.js component, I'd like to add a background color to any checkbox that is clicked:

<div class="langs-container">

    <div class="lang">
        <input type="checkbox"   value="English"   class="mycheckbox" v-model="languages">
        English
    </div>
    <div class="lang">
        <input type="checkbox"   value="French"   class="mycheckbox" v-model="languages">
        French
    </div>

</div>

So let's say we want to add green to each checkbox that is active (ticked) and remove it when unticked:

.green {
 background-color: green;
}

What's the idomatic way to achieve this?

Update: languages is an array, so I can not define English and French as false by default.

2
  • use class binding vuejs.org/v2/guide/class-and-style.html Commented Sep 18, 2018 at 11:30
  • Please elaborate your answer, I saw that page but can not apply it to this particular case. Commented Sep 18, 2018 at 12:22

1 Answer 1

4

Give each checkbox a v-model which is used for class binding.

Distinguish the two checkboxes by using an object for the input as v-model:

<input v-model="languages.english"...>

Use class binding based on that:

<div class="lang" :class="{ 'green': languages.english }">

UPDATE:

As requested in the comments, here is a solution for languages as array (instead of object), which is not as "clean" anymore:

You need an additional method to return true or false based on the checked values.

new Vue({
  el: "#app",
  data() {
    return {
      languages: []
    }
  },
  methods: {
    isChecked(value) {
     return this.languages.includes(value)
    }
  }
})
.green {
 background-color: green;
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<div id="app">
  <div class="langs-container">

    <div class="lang" :class="{ 'green': isChecked('English') }">
      <input type="checkbox" value="English" class="mycheckbox" v-model="languages"> English
    </div>
    <div class="lang" :class="{ 'green': isChecked('French') }">
      <input type="checkbox" value="French" class="mycheckbox" v-model="languages"> French
    </div>

  </div>
</div>

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

2 Comments

Well, the issue is that in my case, languages is expected to be an array, not an object. So this solution is not applicable, at least in present shape.
@Babr Updated my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.