2

Just started using Vue.js so lots to learn. I want to change the background color when an input is disabled because a computed function returns true. I can't seem to make it work.

This is in my export default

computed: {
  disableField () {
    if (condition) return true
  }
}

This is in my template

<input
  :class="{ disableInput: disableField }"
  :disabled="disableField"
/>

This is in my CSS

.disable-input {
  background-color: gray;
}

It disables the field when the computed function returns true but it doesn't change the background color.

2 Answers 2

6

As @dziraf pointed out, your class name is 'disable-input', so change it to :class="{'disable-input': disabled}", then should work fine.

Or if this input only bind this class, uses :class="disabled ? 'disable-input' : ''" is another solution.

Or you may want to use css selector to implement same goal, like:

input:disabled { background-color:red; }

Below is one demo:

new Vue({
  el: '#app',
  data () {
    return {
      disabled: true
    }
  }
})
input:disabled {
  background-color:red;
}

input.disable-input {
  background-color: gray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
<div id="app">
  <button @click="disabled=!disabled">Toggle {{disabled}}</button>
  <input :disabled="disabled" :value="'abc'">
  <input :disabled="disabled" :value="'abc'" :class="{'disable-input': disabled}">
  <input :disabled="disabled" :value="'abc'" :class="disabled ? 'disable-input' : ''">
</div>

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

Comments

1

Corrected syntax below. Enclose your classname in quotes.:

<input
  :class="{ 'disableInput': disableField }"
  :disabled="disableField"
/>

3 Comments

It should be 'disable-input'.
@dziraf You're right. disable-input works. Thank you! This blog that I was reading about Vue.js said to use camel case :(
Just read official documentation, it's very good and this topic is covered there too.

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.