vue中動態(tài)添加style樣式的幾種寫法總結
vue動態(tài)添加style樣式總結
項目中可能會需要動態(tài)添加 style 行內樣式,但是在長期維護的項目里面,盡量要避免使用。
注意:
1、凡是有 - 的style屬性名都要變成駝峰式,比如font-size要變成fontSize。
2、除了綁定值,其他的屬性名的值要用引號括起來,比如backgroundColor:'#00a2ff'而不是 backgroundColor:#00a2ff。
對象
html :style="{ color: activeColor, fontSize: fontSize + 'px' }"
html :style="{color:(index==0?conFontColor:'#000')}"數組
html :style="[baseStyles, overridingStyles]"
html :style="[{color:(index==0?conFontColor:'#000')},{fontSize:'20px'}]"三目運算符
html :style="{color:(index==0?conFontColor:'#000')}"
html :style="[{color:(index==0?conFontColor:'#000')},{fontSize:'20px'}]"多重值(瀏覽器會根據運行支持情況進行選擇)
html :style="{ display: ['-webkit-box', '-ms-flexbox', 'flex'] }"綁定data對象
html :style="styleObject"
?
data() {
? ? return{
? ? ? styleObject: {
? ? ? ? color: 'red',
? ? ? ? fontSize: '13px'
? ? ? } ?
? ? }
}vue3的style樣式的特性
scoped 屬性
定義的 CSS 就只會應用到當前組件的元素上,這樣就很好地避免了一些樣式沖突的問題。
我們項目中的樣式也可以加上如下標簽:
<style scoped>
h1 {
color: red;
}
</style>>這樣,組件就會解析成下面代碼的樣子。標簽和樣式的屬性上,新增了 data- 的前綴,確保只在當前組件生效。
<h1 data-v-3de47834="">1</h1>
<style scoped>
h1[data-v-3de47834] {
color: red;
}
</style>在 scoped 內部,寫全局的樣式
可以用:global 來標記,這樣能確保你可以很靈活地組合你的樣式代碼
通過v-bind 函數,在 CSS 中使用 JavaScript 中的變量
<template>
<div>
<h1 @click="add">{{ count }}</h1>
</div>
</template>
<script setup>
import { ref } from "vue";
let count = ref(1)
let color = ref('red')
function add() {
count.value++
color.value = Math.random()>0.5? "blue":"red" // 隨機生成一個0-1之間點數字
}
</script>
<style scoped>
h1 {
// v-bind 函數綁定 color 的值
color:v-bind(color);
}
</style>>點擊累加器時文本顏色的切換效果,如下圖所示:

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Vue實現Tab標簽路由效果并用Animate.css做轉場動畫效果的代碼
這篇文章主要介紹了Vue實現Tab標簽路由效果,并用Animate.css做轉場動畫效果,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-07-07
vue使用elementui的el-menu的折疊菜單collapse示例詳解
這篇文章主要介紹了vue使用elementui的el-menu的折疊菜單collapse示例詳解,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-12-12

