增加方法:1、用“:class=['类名']”语句添加;2、用“:class=['类名1','类名2',{属性名(类名):'属性值(true或false)}]”语句;3、用“:class={属性名(类名):true}”语句;4、用“:style={'样式名':'样式值'}”语句;5、用“:style=样式”语句增加;6、用“:style=[data]”语句。
本教程操作环境:windows7系统、vue3版,dell g3电脑。
vue中的添加样式一、使用class样式:类名必须用引号 引起来;
1、数组
<h1 :class = "['类名1','类名2']">这种方法 需要用 v-bind: => : 绑定</h1>
2、数组中使用三元表达式
<h1 :class = "['类名1','类名2',表达式?'类名3':'']">这种方法 需要用 v-bind: => : 绑定</h1>
3、数组中嵌套对象
<h1 :class = "['类名1','类名2',{属性名(类名):'属性值(true或false)}]">这种方法 需要用 v-bind: => : 绑定</h1>
4、直接适用对象
<h1 :class = "{属性名(类名1):true,属性名(类名2):true}">这种方法 需要用 v-bind: => : 绑定</h1>
二、使用内联样式;1、直接在元素上通过 :style 的形式
<h1 :style = "{'样式名':'样式值'}">这种方法 需要用 v-bind: => : 绑定</h1>
2、将样式对象,定义到data 中,在引用到 :style 中
<h1 :style = "vue里的样式">这种方法 需要用 v-bind: => : 绑定</h1>
3、在 :style 中通过数组,引用多个 data 上的样式对象;
<h1 :style = "[data1,data2]">这种方法 需要用 v-bind: => : 绑定</h1>
代码实例:
<!doctype html><html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title>vue样式的运用</title> <style> * { margin: 0; padding: 0; } .box { width: 150px; height: 150px; background: skyblue; line-height: 150px; text-align: center; } .border { border-radius: 50%; } .color { color: #fff; font-size: 24px; } </style></head><body> <div id="app"> <button @click="tagger = !tagger">切换</button> <!-- 添加样式/切换样式 --> <!-- 对象方式 border 数据模型 tagger 真假 真显示 假隐藏--> <!-- <div class="box" :class="{'border':tagger}">添加style样式</div> --> <!-- 表达式 --> <!-- <div :class="tagger ? 'border' : ''" class="box">添加style样式</div> --> <!-- 数组 --> <div :class="tagger ? ['box','border'] : ['box']">添加style样式</div> </div> <script src="https://cdn.jsdelivr.net/npm/vue"></script> <script> let vm = new vue({ el: '#app', data: { tagger : true, vstyle : ['border','box'], vobj : {border:true,color:true,box:true} }, methods: { } }) </script></body></html>
(学习视频分享:vuejs入门教程、编程基础视频)
以上就是vue怎么在元素上增加样式的详细内容。