黄子涵

4.3.3 绑定内联样式

使用 v-bind:style(即 :style)可以给元素绑定内联样式,方法与 :class 类似。也存在对象语法和数组语法,看起来很像在元素上直接写 css。

在 components 文件夹下新建 BindStyle.vue 组件,写入如示例 11 所示代码,并在路由 index.js 中进行配置。

示例 11

App.vue
<template>
<HzhBindStyle>黄子涵</HzhBindStyle>
</template>
<script>
import HzhBindStyle from './components/hzhBindStyle.vue';
export default {
name: 'APP',
data() {
return {
};
},
components: {
HzhBindStyle,
}
};
</script>
<style scoped>
.static {
margin: 5px 0;
font-size: 20px;
}
.active {
text-align: center;
width: 60px;
border: 1px solid #000;
}
.danger {
background: #ff0;
}
</style>

HzhBindStyle.vue

<template>
<div :style="{ border: activeColor, fontSize: fontSize + 'px'}">黄子涵:绑定内联样式</div>
</template>
<script>
export default {
name: 'HzhBindStyle',
data() {
return {
activeColor: "1px solid #000",
fontSize: 22
};
}
};
</script>
<style>
</style>

在浏览器中运行,显示效果和渲染结果如下图所示。

image

大多数情况下,直接写一长串的样式不便于阅读和维护,因此实际的开发中往往是写在 data 或者computed 计算属性里。下面以 data 的形式来改写示例 11,代码如下所示。

<template>
<div :style="styles">黄子涵:绑定内联样式</div>
</template>
<script>
export default {
name: 'HzhBindStyle',
data() {
return {
styles: {
width: 220 + 'px',
border: '1px solid #000',
fontSize: 22 + 'px'
}
};
}
};
</script>
<style>
</style>

image

在使用 :style 时,Vue.js 会自动给特殊的 css 属性名称增加前缀,比如 transform 属性 。

posted @   黄子涵  阅读(40)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示