3

I would like to apply a computed style to an input form. The documentation explains how to do that, but only for simple styles.

I need to apply the equivalent of

input[type="text"], textarea {
  background-color : red; 
}

but it is not clear for me how to convey the [type="text"] bit.

Using it verbatim does not work:

var vm = new Vue({
  el: "#root",
  data: {
    password: '',
  },
  computed: {
    passwordStyle: function() {
      var style = {}
      style['input[type="text"]'] = 'red';
      style['textarea'] = 'blue';
      return style;
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.min.js"></script>
<div id="root>">
  <input type="text" name="password" autofocus="true" v-bind:style='passwordStyle'>
</div>

2 Answers 2

2

You need to only pass the style, not the css selector, like:

var vm = new Vue({
  el: "#root",
  data: {
    password: '',
  },
  computed: {
    passwordStyle: function() {
      return {
        backgroundColor: 'red'
      };
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.min.js"></script>
<div id="root">
  <input type="text" name="password" autofocus="true" :style="passwordStyle">
</div>

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

1 Comment

Thank you. I was so focused on my code that I did not realise that in the example I forgot to pass background-color at all...
1

Can you explain your use-case little bit elaborately, use of v-bind:style is when you want to dynamically change the style of some element, depending on some variable, as it is in docs, following code with change the CSS depending on isActive and hasError variable:

<div class="static"
     v-bind:class="{ active: isActive, 'text-danger': hasError }">
</div>

data: {
  isActive: true,
  hasError: false
}

I don't see in your code you are changing style based on any variable.

2 Comments

This is true, my example was to a minimal one to just have the styles applied. In reality passwordStyle will be computed based on a complex set of rules, using other elements of the vm data variables.
@WoJ Can you add that use case in little more detail.

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.