美文网首页
计算属性的get和set

计算属性的get和set

作者: 63537b720fdb | 来源:发表于2020-07-16 00:35 被阅读0次

1.稍复杂操作案例

做字符串拼接时,可以使用插值操作显示出效果,但是在一些情况下,插值操作没有办法替代计算属性

    <div id="app">
        <h2>总价格:{{totalPrice}}</h2>
    </div>
        const app = new Vue({
            el : '#app',
            data : {
                books : [
                    {id : 000, name : 'HTML', price : 56},
                    {id : 001, name : 'CSS', price : 68},
                    {id : 002, name : 'JS', price : 79},
                ]
            },
            computed : {
                totalPrice : function () {
                    var result = 0;
                    for(var i = 0; i < this.books.length; i++) {
                        result += this.books[i].price;
                    }
                    return result;
                }
                
            }
        })
image.png

2.geter和seter

每个计算属性都有一个getter和setter,完整的computed属性如下:
totalPrice和fullName计算属性都有get属性和set属性

            computed : {
                totalPrice : {
                    get : function() {

                    },
                    set : function() {

                    }
                },
                fullName : {
                    get : function() {

                    },
                    set : function() {
                        
                    }
                }
            }
image.png

大多数的计算属性只使用到get方法,所以可以简化成第一种写法,也导致会将totalPrice误认成函数,toltalPrice只是一个计算属性,所以在插值操作时,不能写成toltalPrice()

1.使用get来获取数据


image.png

2.虽然set很少使用,但是也可以使用


image.png
image.png

相关文章

网友评论

      本文标题:计算属性的get和set

      本文链接:https://www.haomeiwen.com/subject/vatshktx.html