Vue-样式绑定-style

发布于:2025-05-20 ⋅ 阅读:(18) ⋅ 点赞:(0)

样式绑定-style

  • 对象写法
  • 数组写法

对象写法

:style="{fontSize: x}", x是动态值 ({fontSize: x}是样式对象)

  • 代码
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>样式绑定-style</title>
    <!--  引入Vue  -->
    <script type="text/javascript" src="../js/vue.js"></script>
    <style>
        .base{
            padding: 5px;
            height: 100px;
        }
    </style>
  </head>
  <body>
    <div id="root">
      <h1>样式绑定-style</h1>
      <div>
        <h2>样式绑定-style-对象写法</h2>
        <!-- 
            style样式绑定 - 对象写法
        -->
        <div class="base" :style="bgcObj">{{name}}</div><br>
      </div>
    </div>
  </body>
  <script type="text/javascript">
    Vue.config.productionTip = false; // 阻止vue在启动是生成生产提示
    const vm = new Vue({
      el: "#root",
      data: {
        name: "Vue 扛把子",
        bgcObj:{
          fontSize: '40px',
          backgroundColor: 'orange'
        },
        bgcObj2:{
          color: 'blue'
        },
      },
      
      methods:{
      },
    });
  </script>
</html>

  • 效果

在这里插入图片描述

数组写法

:style=[styleObj1,styleObj2], styleObj1、2均是样式对象

  • 代码
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>样式绑定-style</title>
    <!--  引入Vue  -->
    <script type="text/javascript" src="../js/vue.js"></script>
    <style>
        .base{
            padding: 5px;
            height: 100px;
        }
    </style>
  </head>
  <body>
    <div id="root">
      <h1>样式绑定-style</h1>
      <div>
        <h2>样式绑定-style-数组写法</h2>
        <!-- 
            style样式绑定 - 数组写法
        -->
        <div class="base" :style="bgcArr">{{name}}</div><br>
      </div>
    </div>
  </body>
  <script type="text/javascript">
    Vue.config.productionTip = false; // 阻止vue在启动是生成生产提示
    const vm = new Vue({
      el: "#root",
      data: {
        name: "Vue 扛把子",
        bgcObj:{
          fontSize: '40px',
          backgroundColor: 'orange'
        },
        bgcObj2:{
          color: 'blue'
        },
        bgcArr:[
          {
            fontSize: '40px',
            backgroundColor: 'orange'
          },
          {
            color: 'blue'
          }

        ]
      },
      
      methods:{
      },
    });
  </script>
</html>

  • 效果

在这里插入图片描述


网站公告

今日签到

点亮在社区的每一天
去签到