Vue 绑定style简介
绑定style样式对应HTML 元素的 style 属性,比如要设置字段大小:
<div :style="{fontSize: '2rem'}">你好,中国!</div>
样式名称建议采用驼峰写法,但是也可以用 kebab-cased 的形式,比如上例中,也可以写成:
<div :style="{'font-size': '2rem'}">你好,中国!</div>
对象来设置
<template>
<div :style="fontSet">你好,中国!</div>
</template>
<script setup>
const fontSet = {
'font-size': '2rem',
'color': '#ff0000',
'font-weight': 'bold',
'textIndent': '2rem'
}
</script>
计算属性来设置
<template>
<div :style="fontSet">你好,中国!</div>
</template>
<script setup>
import {
ref,
computed
} from 'vue'
const fontSize = ref(2)
const fontColor = ref('#ff0000')
const fontSet = computed(()=>({
'font-size': fontSize.value + 'rem',
'color': fontColor.value
}))
</script>
数组来设置
<template>
<div :style="[fontSize, fontColor]">你好,中国!</div>
</template>
<script setup>
import {
ref,
computed
} from 'vue'
const fontSize = ref({
'font-size': '2rem'
})
const fontColor = ref({
'color': '#ff0000'
})
</script>

浙公网安备 33010602011771号