<html><head><scriptsrc="https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.js"></script><style>.red{color: red;}.fs30{font-size: 30px;}</style></head><body><divid="app"><div:class="{red:true}">显示红色字体</div><div:class="{'red':true}">显示红色字体</div><div:class="{'red':flag}">显示红色字体</div><div:class="{'red':'flag'}">显示红色字体</div></div></body><script>let vm =newVue({el:"#app",data:{flag:true},methods:{}})</script></html>
数组内置对象
<html><head><scriptsrc="https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.js"></script><style>.red{color: red;}.fs30{font-size: 30px;}</style></head><body><divid="app"><div:class="[{red:true},{fs30:flag}]">红色字体、字号30px</div><div:class="[{'red':flag},{fs30:'flag'}]">红色字体、字号30px</div></div></body><script>let vm =newVue({el:"#app",data:{flag:true},methods:{}})</script></html>
二、使用style样式
直接在元素上通过 :style 的形式,书写样式对象
<html><head><scriptsrc="https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.js"></script></head><body><divid="app"><!-- 键如果包含-的话,必须要加上引号 --><div:style="{color : 'red','font-size' : '30px'}">红色字体、字号30px</div></div></body><script>let vm =newVue({el:"#app",data:{},methods:{}})</script></html>
对象
<html><head><scriptsrc="https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.js"></script></head><body><divid="app"><div:style=style1>红色字体</div><div:style=style2>字号30px、字体加粗</div></div></body><script>let vm =newVue({el:"#app",data:{style1:'color:red',style2:{fontSize:"30px","font-weight":700}},methods:{}})</script></html>
数组内置对象
<html><head><scriptsrc="https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.js"></script></head><body><divid="app"><div:style='[style1,style2]'>红色字体、字号30px、字体加粗</div></div></body><script>let vm =newVue({el:"#app",data:{style1:{'color':'red'},style2:{fontSize:"30px","font-weight":700}},methods:{}})</script></html>
函数返回值
<html><head><scriptsrc="https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.js"></script></head><body><divid="app"><div:style='getStyle()'>字号30px、字体红色</div></div></body><script>let vm =newVue({el:"#app",data:{},methods:{getStyle(){return{color:'red',fontSize:"30px",}}}})</script></html>