2017-01-24 29 views
2

我想將computed樣式應用於輸入表單。 documentation解釋瞭如何做到這一點,但只適用於簡單的樣式。如何在vue.js中使用屬性選擇器?

我需要申請的

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

相當於目前尚不清楚對我如何傳達[type="text"]

使用它逐字不起作用:

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>

回答

1

您只需要通過風格,而不是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>

+0

謝謝。我很專注於我的代碼,我沒有意識到,在這個例子中,我忘了通過'background-color' ...... – WoJ

0

你能不能有點精心解釋你的用例,使用v-bind:style是當你需要動態改變某些元素的樣式,取決於某些變量,因爲它在文檔中,下面的代碼通過更改CSS取決於isActivehasError變量:

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

data: { 
    isActive: true, 
    hasError: false 
} 

我沒有看到你的代碼中你正在改變基於任何變量的風格。

+0

這是真的,我的例子是最小的一個,只是已經應用的樣式。實際上'passwordStyle'將根據一組複雜的規則計算,使用'vm''data'變量的其他元素。 – WoJ

+0

@WoJ你可以稍微詳細一點地添加該用例。 – Saurabh

相關問題