vue如何在style標簽中使用變量(數據)詳解
參考資料
在 style 中使用 data 變量
options 方式:
<template>
<div class="text">hello</div>
</template>
<script>
export default {
data() {
return {
color: 'red'
}
}
}
</script>
<style>
.text {
color: v-bind(color);
}
</style>Composition 方式
<script setup>
const theme = {
color: 'red'
}
</script>
<template>
<p>hello</p>
</template>
<style scoped>
p {
color: v-bind('theme.color');
}
</style>還有一個問題,如果我們的變量是數字,但是我們想要設置像素怎么辦?
其實這個很好解決
一種是使用 computed 計算屬性改變它
<script setup>
import { computed } from 'vue';
const props = defineProps({ size: Number });
const sizePx = computed(() => `${props.size}px`)
</script>
<template>
<p>hello</p>
</template>
<style scoped>
p {
font-size: v-bind(sizePx);
}
</style>還有一種方式是使用 calc css 計算屬性
<script setup>
defineProps({ size: Number });
</script>
<template>
<p>hello</p>
</template>
<style scoped>
p {
font-size: calc(1px * v-bind(size));
}
</style>當然還有第三種那就是傳值的時候就傳成字符串格式
option 方式大同小異
==========================================================================================
那么如何在代碼中使用style屬性呢?
也很簡單
同樣參考
<template>
<p :class="$style.red">This should be red</p>
</template>
<style module>
.red {
color: red;
}
</style>還可以設置不同的變量
<template>
<p :class="classes1.red">This should be red</p>
</template>
<style module="classes1">
.red {
color: red;
}
</style>
<style module="classes2">
.red {
color: green;
}
</style>如果是在 script 中使用,可以使用 useCssModule
import { useCssModule } from 'vue';
const classes1 = useCssModule('classes1');
const classes2 = useCssModule('classes2');總結
到此這篇關于vue如何在style標簽中使用變量(數據)的文章就介紹到這了,更多相關vue在style標簽使用變量內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
使用vue初用antd 用v-model來雙向綁定Form表單問題
這篇文章主要介紹了使用vue初用antd 用v-model來雙向綁定Form表單問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-04-04
vue內置組件keep-alive事件動態(tài)緩存實例
這篇文章主要介紹了vue內置組件keep-alive事件動態(tài)緩存實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-10-10

