Vue.js绑定内联样式

时间:2023-03-09 08:23:51
Vue.js绑定内联样式

1.对象语法

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!--引入Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<title>无标题文档</title>
</head> <body>
<!--<div id="box" :style="{color:activeColor, font-size:size}">用短横分隔是会报错</div>-->
<div id="box" :style="{color:activeColor, fontSize:size, textShadow:shadow}">没有短横分隔不报错</div> <div id="box2" :style="styleObject">工作睡觉吃饭</div>
</body>
</html>
<script type="text/javascript">
// v-bind:style 的对象语法十分直观--非常像CSS,其实它是一个Javascript对象,CSS属性名必须用驼峰命名法(官方文档写的是既可以用驼峰也可以用 短横分隔命名法),但是用短横分隔是会报错的
var vm= new Vue({
el:'#box',
data:{
activeColor:'#f00',
size:'30px',
shadow:'5px 2px 6px #000'
}
}) var vm= new Vue({
el:'#box2',
data:{
styleObject:{
color:'red',
fontSize:'30px'
}
}
})
</script>

效果图

Vue.js绑定内联样式

2.数组语法

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!--引入Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<title>无标题文档</title>
</head> <body>
<div class="box" :style="[styleObjectA, styleObjectB]">好好学习,天天向上</div>
</body>
</html>
<script type="text/javascript">
// 可将多个样式对象应用到一个元素上
var vm2= new Vue({
el:'.box',
data:{
styleObjectA:{
fontSize:'36px',
color:'blue'
},
styleObjectB:{
textDecoration:'underline'
}
}
})
</script>

效果图:

Vue.js绑定内联样式

3.添加图片src地址

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!--引入Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<title>无标题文档</title>
</head> <body>
<!--
下面这种写法不会显示图片,会报错,推荐第二种写法
<img class="box" src="{{url}}" >
--> <img class="box" :src="url" >
</body>
</html>
<script type="text/javascript">
var vm= new Vue({
el:'.box',
data:{
url:'https://bbsfiles.vivo.com.cn/vivobbs/attachment/forum/201809/12/005629z489rqqeeyle7gje.jpg.thumb.jpg'
}
})
</script>

效果图:

Vue.js绑定内联样式