classをデータにバインディング(紐付け)する
パターン1
<div id="app">
<h1 :class="classObject">Text</h1>
<button @click="isActive = !isActive">switch</button>
</div>
<style>
.red {
color: red;
}
.bg-blue {
background-color: blue;
}
</style>
<script>
new Vue({
el: "#app",
data: {
isActive: true
},
computed: {
classObject: function () {
return {
red: this.isActive,
'bg-blue': !this.isActive
}
}
},
})
</script>
パターン2
<div id="app">
<h1 :class="classObject">Text</h1>
<button @click="isActive = !isActive">switch</button>
</div>
<style>
.red {
color: red;
}
.bg-blue {
background-color: blue;
}
</style>
<script>
new Vue({
el: "#app",
data: {
isActive: true
},
computed: {
classObject: function () {
return {
red: this.isActive,
'bg-blue': !this.isActive
}
}
},
})
</script>
styleをデータにバインディング(紐付け)する
<div id="app">
<h1 :style="{ color: textColor, 'background-color': bgColor }">Text</h1>
<h1 :style="styleObject">Text</h1>
</div>
<script>
new Vue({
el: "#app",
data: {
textColor: 'red',
bgColor: 'blue',
styleObject: {
color: 'red',
'background-color': 'blue'
}
}
})
</script>