v-bind:style style属性にbindする
var app1 = new Vue({ el: '#app1', data: { titleFontColor: "red", h2Color:"blue" } })
HTMLにはオブジェクトを埋め込む。styleのキー要素は-(ハイフン)がキャメルケースとなる。
<h2 v-bind:style="{color:titleFontColor, backgroundColor:h2Color}">Title</h2>
または、クォートすればstyleのキー要素のまま記述できる。
<h2 v-bind:style="{color:titleFontColor, 'background-color':h2Color}">Title</h2>
style属性にオブジェクトを指定する
var app1 = new Vue({ el: '#app1', data: { titleFontColor: "red", h2Color:"blue", h2Style:{ color:"yellow", backgroundColor:"black" }, addStyle:{ fontSize:"100px" } } });
複数指定する場合[]
配列にする
<h2 v-bind:style="h2Style">Title</h2> <h2 v-bind:style="[h2Style,addStyle]">Title</h2>
v-bind:class class属性にbindする
指定オブジェクトの値true:falseで有効/無効を指定する
<style> .frame { border-style: solid; padding: 10px; margin: 10px; } .warn{ color:red; } .warn-fontsize{ font-size: 5em; } </style> <h2 v-bind:class="{warn:true, 'warn-fontsize':true }">Title</h2> <h2 v-bind:class="{warn:true, 'warn-fontsize':false }">Title</h2>
class属性にVueオブジェクトの属性をbindする
<style> .frame { border-style: solid; padding: 10px; margin: 10px; } .warn{ color:red; } .warn-fontsize{ font-size: 5em; } </style> <h2 v-bind:class="[warnClass, warnFontsizeClass]">Title</h2>
var app1 = new Vue({ el: '#app1', data: { warnClass:"warn", warnFontsizeClass:"warn-fontsize" } });
当然リアクティブとなるので、warnClassやwarnFontsizeClassの値を変更すると別のclassになる。
サンプルコード
Vue-Samples/stylebind.html at master · letitride/Vue-Samples · GitHub
リンク