Vue.jsでは、v-bindでclass属性を設定した際に、下記の様なオブジェクトを渡すことにより、class属性の値を適用、不適用を切り替えることができる。
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.js"></script>
<style>
.red {
background-color: red;
}
.blue {
background-color: blue;
}
</style>
<div id="app">
<h1 :class="{red:true, blue:false}">Hello</h1>
</div>
<script>
new Vue({
el: '#app',
})
</script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.js"></script>
<style>
.red {
background-color: red;
}
.blue {
background-color: blue;
}
</style>
<div id="app">
<h1 :class="{red:false, blue:true}">Hello</h1>
</div>
<script>
new Vue({
el: '#app',
})
</script>
##v-bindされたclass属性の値にオブジェクトを渡して動的に切り替える。
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.js"></script>
<style>
.red {
background-color: red;
}
.blue {
background-color: blue;
}
</style>
<div id="app">
<h1 :class="classChange">Hello</h1>
<button @click="change">切り替え</button>
</div>
<script>
new Vue({
el: '#app',
data: {
isActive: true
},
methods: {
change: function () {
this.isActive = !this.isActive
},
},
computed: {
classChange: function () {
return {
red: this.isActive,
blue: !this.isActive,
}
}
}
})
</script>
データの流れ