8.1 class 与 style 绑定

8.1.1 理解

  1. 在应用界面中, 某个(些)元素的样式是变化的
  2. class/style 绑定就是专门用来实现动态样式效果的技术

    8.1.2 class 绑定

  3. :class='xxx',xxx 可以是字符串、数组、对象

  4. 表达式是字符串: 'classA'
  5. 表达式是对象: {classA:isA, classB: isB},其中 isA 和 isB 是动态值
  6. 表达式是数组: ['classA', 'classB']'classA', 'classB'是已定义好的样式对象

使用场景:

  • 字符串写法适用于:类名不确定,要动态获取。
  • 对象写法适用于:要绑定多个样式,个数不确定,名字也不确定。
  • 数组写法适用于:要绑定多个样式,个数确定,名字也确定,但不确定用不用。

    • image.pngimage.png

      代码演示

      ```html <!DOCTYPE html>

      {{name}}


      {{name}}


      {{name}}


  1. <a name="es72F"></a>
  2. ## 8.1.3 style 绑定
  3. `:style="{ color: activeColor, fontSize: fontSize + 'px' }"`,其中 `activeColor/fontSize `是 `data `属性。
  4. - `:style="{fontSize: xxx}"`其中`xxx`是动态值。
  5. - `:style="[a,b]"`其中`a、b`是样式对象。
  6. <a name="f5GLd"></a>
  7. ### 代码演示
  8. ```html
  9. <!DOCTYPE html>
  10. <html>
  11. <head>
  12. <meta charset="UTF-8" />
  13. <title>绑定样式</title>
  14. <style>
  15. .basic{
  16. width: 400px;
  17. height: 100px;
  18. border: 1px solid black;
  19. }
  20. .happy{
  21. border: 4px solid red;;
  22. background-color: rgba(255, 255, 0, 0.644);
  23. background: linear-gradient(30deg,yellow,pink,orange,yellow);
  24. }
  25. .sad{
  26. border: 4px dashed rgb(2, 197, 2);
  27. background-color: gray;
  28. }
  29. .normal{
  30. background-color: skyblue;
  31. }
  32. .atguigu1{
  33. background-color: yellowgreen;
  34. }
  35. .atguigu2{
  36. font-size: 30px;
  37. text-shadow:2px 2px 10px red;
  38. }
  39. .atguigu3{
  40. border-radius: 20px;
  41. }
  42. </style>
  43. <script type="text/javascript" src="../js/vue.js"></script>
  44. </head>
  45. <body>
  46. <!-- 准备好一个容器-->
  47. <div id="root">
  48. <!-- 绑定style样式--对象写法 -->
  49. <div class="basic" :style="styleObj">{{name}}</div> <br/><br/>
  50. <!-- 绑定style样式--数组写法 -->
  51. <div class="basic" :style="styleArr">{{name}}</div>
  52. </div>
  53. </body>
  54. <script type="text/javascript">
  55. Vue.config.productionTip = false
  56. const vm = new Vue({
  57. el:'#root',
  58. data:{
  59. name:'尚硅谷',
  60. styleObj:{
  61. fontSize: '40px',
  62. color:'red',
  63. },
  64. styleObj2:{
  65. backgroundColor:'orange'
  66. },
  67. styleArr:[
  68. {
  69. fontSize: '40px',
  70. color:'blue',
  71. },
  72. {
  73. backgroundColor:'gray'
  74. }
  75. ]
  76. }
  77. })
  78. </script>
  79. </html>

总而言之,所有需要动态变更的样式都要放到Vue属性里进行管理