Vue.js computed 例子 class与style绑定

本文通过一个具体的示例介绍了 Vue.js 中计算属性的使用方法,特别是如何实现数据的实时更新。同时展示了如何利用 v-bind 动态绑定 class 和 style 的技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>vue学习</title>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
    <div id="app1">
        <h4>{{fullName}}</h4>
    </div>
    <script>
        var foo = new Vue({
            el: '#app1',
            data: {
                firstName: 'Foo',
                lastName: 'Bar',
            },
            //computed 就是计算属性,特别常用  适用于 它的值是通过data数据得到的
            computed: {
                fullName: {                                   //实时计算属性 下面包括要实时计算的属性
                    get: function () {                         //这是一个getter  return出来东西的
                        return this.firstName + ' ' + this.lastName
                    },
                    set: function (newValue) {                     //setter 赋值 
                        var names = newValue.split(' ');
                        this.firstName = names[0];
                        this.lastName = names[names.length - 1]
                    }
                }
            }

        });
        foo.fullName = 'A sun';                          //调用setter赋值
        alert(foo.firstName);
    </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>vue学习</title>
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<style>
.isActive{
opacity: 0.5;
}
.color{
color: red;
font-size: 24px;
}
.abc{
background: #333333;
}
</style>
</head>
<body>
<div id="app1">
<h5 v-bind:class="['isActive','color']" class="abc">sfsdfsd</h5> <!--数组语法 -->
<mycomp v-bind:class="{isActive,color}"></mycomp> <!--模版下 绑定class-->
<h6 v-bind:style="{'font-size':'20px','display': ['-webkit-box', '-ms-flexbox', 'flex']}">dfdfdf</h6>
</div>
<script>
var foo = new Vue({
el:'#app1',
data:{
isActive:true,
color:true,
styleObj:{
color:'yellow'
}
},
components:{
'mycomp':{
template:'<p class="abc">组件下的class</p>'
}
}
});
</script>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值