Failure is part of learning. we should never give up the struggle in life

Vue学习笔记-计算属性

计算属性是指通过一系列运算后,最终得到一个属性值
这个动态计算出来的属性值可以被模板结构或methods方法使用
例:
不用计算属性写法
利用字符串的拼接

<script src="./vue.js"></script>
    <style>
        .box {
            width: 200px;
            height: 200px;
            border: 1px solid #ccc;
        }
    </style>
</head>

<body>
    <div id="app">
        <div>
            <span>R:</span>
            <input type="text" v-model.number='r'>
        </div>
        <div>
            <span>G:</span>
            <input type="text" v-model.number='g'>
        </div>
        <div>
            <span>B:</span>
            <input type="text" v-model.number='b'>
        </div>
        <hr>
        <!-- 呈现颜色的盒子 此处:代表v-bind属性绑定 绑定样式对象键为样式属性值在:后-->
        <div class="box" :style='{backgroundColor:`rgb(${r},${g},${b})`}'>
            {{ `rgb(${r},${g},${b})` }}
        </div>
        <button @click='show'>按钮</button>
    </div>
    <script>
        const vm = new Vue({
            el: '#app',
            data: {
                //红色
                r: 0,
                //绿色
                g: 0,
                //蓝色
                b: 0
            },
            methods: {
                show() {
                    console.log(`rgb(${this.r},${this.g},${this.b})`);
                }
            },

        })
    </script>
</body>

这样写不方便复用修改

利用计算属性:

//所有的计算属性放在
computed:{}

将上文例子进行修改

//计算属性在定义的时候,要定义成"方法格式"
            computed: {
                //rgb作为一个计算属性,被定义成了方法格式
                //最终在此方法中要返回一个生成好的rgb(x,x,x)的字符串
                rgb: function () {
                    return `rgb(${this.r},${this.g},${this.b})`
                }
            }

此时调用时直接调用rgb即可 不用字符串拼接

发表评论

电子邮件地址不会被公开。 必填项已用*标注