Vue 动态属性数据绑定_vue3 el-option动态绑定数据

<h2 v-bind:class="{css类名1: true|false, css类名2: true|false}">{{message}}</h2>

问题:我们使用了v-bind:class,那么class属性还能不能用了?
答:可以,完全不耽误,vue会帮你将二者合并

<h2 v-bind:class="{css类名1: true|false, css类名2: true|false}" class="css类名3">{{message}}</h2>

实现一个简单的需求:为文字增加颜色,并点击按钮实现颜色的切换。

按钮实现颜色的切换
    <style>
        .green {
            color:  green;
        }
        .red {
            color:  red;
        }
    </style>

<div id="app">
    <h3 v-bind:class="getColour()">{{message}}</h3>
    <button @click="changeColor">点击按钮更换颜色</button>
</div>

<!--从CDN引入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
<script>
    const app = new Vue({
        el: '#app',
        data: {
            message: '“手里没有剑和有剑不用不是一回事”。尊严只在剑锋之上,真理只在大炮射程之内。',
            isRed: true,    //默认显示红色
            isGreen: false
        },
        methods: {
            getColour(){
                return {
                    red : this.isRed,
                    green: this.isGreen
                }
            },
            changeColor(){
                this.isRed = !this.isRed
                this.isGreen = !this.isGreen
            }
        }

    })
</script>

在这里插入图片描述
浏览器效果展示

在这里插入图片描述

v-bind绑定class属性
<style>
        .green {
            color:  green;
        }
        .red {
            color:  red;
        }
        .bold {
            font-weight: 800;
            font-size: 28px;
        }

</style>

<div id="app">
    <h3 v-bind:class="cssArray">{{message}}</h3>
    <button @click="changeColor">点击按钮更换颜色</button>
</div>

<!--从CDN引入vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
<script>
    const app = new Vue({
        el: '#app',
        data: {
            message: '“回忆是一条没有尽头的路,一切以往的春天都不复存在,就连那最坚韧而又狂乱的爱情归根结底也不过是转瞬即逝的现实。\n',
           // isRed: true, //默认显示红色
           // isGreen: false
            cssArray: ['bold','red'] //默认室蓝色
        },
        methods: {
            changeColor(){
                if(this.cssArray[1] !== 'red'){ //如果不是红色
                    this.cssArray.pop();
                    this.cssArray.push('red');
                  // this.cssArray[1] = 'red' //这种写法不是响应式的,数据发生变化时,页面显示的颜色不会改变。
                }else {
                    this.cssArray.pop();
                    this.cssArray.push('green');
                }
            }
        }

    })
</script>

在这里插入图片描述
浏览器页面展示:
在这里插入图片描述

我们使用数组的pop()和push()方法去操作数组元素,而不是使用this.cssArray[1] = 'red'直接操作数组。因为这种通过下标操作数组的方式不是响应式的,也就是说虽然数组元素的值会发生变化,但不会导致页面颜色发生切换

所以,当我们希望通过操作数据影响页面显示内容及显示效果的时候,要使用数组相关的函数,不能直接使用数组下标操作数据。下面列举一下经常用到的响应式的数组操作函数:

  • push(param…) 加入元素到数组的尾部
  • pop() 从数组的尾部弹出一个元素
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值