動態class:綁定HTML class
給 :class (v-bind:class 的縮寫) 傳遞一個物件來動態切換 class
active 是否存在取決於資料屬性 isActive 的真假值
- :class="{ active: isActive }"
- active是 css 的樣式,如果是true 加入active
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <template> <div class="static" :class="{ active: isActive }" > Class </div> <button @click="changeClass">改變Class</button> </template>
<script setup lang="ts"> import { ref, onMounted ,watchEffect,computed} from 'vue'
const isActive =ref<boolean>(false); const changeClass =()=>{ isActive.value =!isActive.value; } </script>
|
動態Style:綁定內聯樣式
- :style="{ color: activeColor, fontSize: fontSize + 'px',backgroundColor: activeColor,}
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| <template> <div class="style" v-bind:style="{ color: activeColor, fontSize: fontSize + 'px',backgroundColor:activeBgColor }">Style</div> <button class="green" @click="changeStyle">改變style</button> </template>
<script setup lang="ts"> import { ref, onMounted ,watchEffect,computed} from 'vue'
const activeColor =ref<string>('red'); const activeBgColor =ref<string>('#ddd'); const fontSize =ref<number>(18);
const changeStyle =()=>{ activeColor.value ='blue'; fontSize.value =19; activeBgColor.value= '#eee'; } </script>
|
Vue動態 Class & Style Github