iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 10
3
Modern Web

超緊繃!30天Vue.js學習日記系列 第 10

[Vue.js][日記]class與style綁定

https://ithelp.ithome.com.tw/upload/images/20190912/20110850dsypfXRkNe.jpg

超緊繃!30天Vue.js學習日記 class與style綁定

大家好,我ian啦!今天要介紹給大家的是:class與style綁定!

  • class綁定

我們先從官方文件做切入,設定一個對象給v-bind,做到動態切換class的功能

<div v-bind:class="{ active: isActive }"></div>

上述範例中, isActive的值(true/false)將會決定active這個class是否存在

同樣的v-bind:class指令也可以跟一般的class屬性共存:

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

JS code:

//在instance中
data: {
  isActive: true,
  hasError: false
}

這樣就會渲染出:

<div class="static active"></div>

這樣做有什麼好處呢?我們可以預先寫好不同class對應的css code,並且動態的切換div的樣式,像是這樣:

<style type="text/css">
	.red{
		color: red;
	}
</style>
<div id="app" :class="{red : isred}">
	{{msg}}
<button @click="update">點我</button>
</div>
<script>
new Vue({
	el:'#app',
	data:{
		msg:'hello world',
		isred:false
	},
	methods:{
		update(){
			let vm = this;
			vm.isred=!vm.isred;
		}
	}
})
</script>

在上述範例中,data內預設的isred為false,當我們按下按鈕時會觸發update()去更新isred的值,變動後,div的class便會產生改變,這樣一來,我們先前寫好的style樣式便會被套用進去!

  • style綁定

寫在物件中內:

<div id="app2" v-bind:style="styleobject">{{msg}}</div>
<script>
var app2 = new Vue({
	el:'#app2',
	data:{
		msg:'styleobject',
		styleobject:{
			color: 'blue',
			fontSize: '25px'
		}
	}
})
</script>

同時綁定多組樣式在該元素中:

<div id="app3" v-bind:style="[styleobject, font]">{{msg}}</div>
<script>
var app3 = new Vue({
	el:'#app3',
	data:{
		msg:'APP3',
		styleobject:{
			color: 'blue',
			fontSize: '25px'
		},
		font:{
			fontFamily: '微軟正黑體'
		}
	}
})
</script>

本日範例:

https://drive.google.com/open?id=1UO-2uBgcYjPuHeNxR_M3M-j7EgrbGH_j

今天的教學到這邊結束,明天會回頭繼續介紹組件(component)!!!


上一篇
[Vue.js][日記]監聽屬性&計算屬性
下一篇
[Vue.js][日記]我還要更多!組件的相關補充
系列文
超緊繃!30天Vue.js學習日記33
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言