vue動態綁定屬性--動態綁定style


動態綁定style

  使用v-bind:style綁定css內聯樣式,寫屬性名時,使用駝峰式或短橫分隔(單引號括起來),如屬性font-size,駝峰式寫法fontSize,短橫寫法:'font-size'

1.對象語法  

  語法格式::style="{屬性名:屬性值,屬性名:屬性值}"

<body>
     <!-- v-bind綁定style--對象語法 (多)-->
     <h2 :style="{fontSize:'50px'}">v-bind綁定style</h2>
     <h2 :style="{fontSize: finalSize + 'px', backgroundColor: finalColor}">v-bind綁定style</h2>
     </div>
     <script src="../js/vue.js"></script>
     <script>
         setTimeout(function() {
           const vm = new Vue({
             el: '#app',
            data: {
               msg: 'hello',
               finalSize: 20,
               finalColor: 'pink',
             }
       });
     },2000);
   </script>
</body>

2.數組語法

<body>

    <!-- v-bind綁定style--數組語法 -->
    <h3 :style="[baseStyle]">v-bind綁定style--數組語法 </h3>

  </div>
  <script src="../js/vue.js"></script>
  <script>
    setTimeout(function() {
      const vm = new Vue({
        el: '#app',
        data: {
          baseStyle: {
            backgroundColor: 'red'
          }
        },
      });
    },2000);
  </script>
</body>

當綁定的對象或數組太長時,可以使用計算屬性或方法將其返回,以對象語法為例

<body>
     <!-- v-bind綁定style--對象語法 (多)-->
     <h2 :style="getStyleObj()">v-bind綁定style--對象語法 (多)-</h2>
     <script src="../js/vue.js"></script>
     <script>
         setTimeout(function() {
           const vm = new Vue({
             el: '#app',
            data: {
               msg: 'hello',
               finalSize: 20,
               finalColor: 'pink',
             },
            methods: {
               getStyleObj(){
                 return {fontSize: this.finalSize + 'px', backgroundColor: this.finalColor}
             }
          },
       });
     },2000);
   </script>
</body>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM