简体   繁体   English

如何在 vue.js 中使用属性选择器?

[英]How to use an attribute selector with vue.js?

I would like to apply a computed style to an input form.我想将computed样式应用于输入表单。 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 .我不清楚如何传达[type="text"]

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>

You need to only pass the style, not the css selector, like:您只需要传递样式,而不是 css 选择器,例如:

 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>

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:您能否详细解释一下您的用例,使用v-bind:style是当您想要根据某些变量动态更改某些元素的样式时,就像在文档中一样,以下代码根据更改 CSS isActivehasError变量:

<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.我没有在您的代码中看到您正在根据任何变量更改样式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM