<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <!-- 导包 -->
    <script src="./vue.js"></script>
    <style>
        div>div {
            width: 100px;
            height: 100px;
            border: 1px solid #000;
            margin-top: 20px;
        }
<pre><code>    .red-box {
        background-color: red;
    }

    .blue-box {
        background-color: blue;
    }

    .greenBorder {
        border: 10px solid green;
    }
&lt;/style&gt;
</code></pre>
</head>
<body>
<pre><code>&lt;!-- HTML结构 --&gt;
&lt;div id=&quot;app&quot;&gt;
    &lt;!-- 本小节内容:Vue设置元素CSS样式的3种方式 --&gt;

    &lt;!--  v-bind:class=&quot;{ '类名': bool, '类名': bool ......}&quot;
            如果值为true 该类样式就会被应用在元素身上, false则不会
            注意点:如果类名有 - ,则需要使用引号包起来
    --&gt;
    &lt;button @click=&quot;changeClass&quot;&gt;切换样式&lt;/button&gt;
    &lt;div :class=&quot;{ 'red-box': flag, 'blue-box': !flag }&quot;&gt;&lt;/div&gt;
    &lt;hr&gt;
    &lt;!-- v-bind:style=&quot;{ 属性名1: 属性值1, 属性名2: 属性值2 ...... }&quot; 
         使用对象的形式,为元素动态设置样式
    --&gt;
    &lt;div :style=&quot;{ width: width, height: height, backgroundColor: bgc }&quot;&gt;&lt;/div&gt;

    &lt;!-- :class 和 :style 可以同时使用 --&gt;
    &lt;div :class=&quot;{ greenBorder: true }&quot; :style=&quot;{ width: '300px', height: '300px' }&quot;&gt;&lt;/div&gt;
&lt;/div&gt;

&lt;script&gt;
    /* 创建vue实例 */
    let app = new Vue({
        //el:挂载点
        el: '#app',
        //data: 要渲染的数据
        data: {
            flag:true,
            width:'200px',
            height:'200px',
            bgc:'green'
        },
        methods: {
            changeClass(){
                this.flag = !this.flag;
            }
        },
    })
&lt;/script&gt;
</code></pre>
</body>
</html>

原文地址: https://www.cveoy.top/t/topic/bMk7 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录