点击左上方“
熊吱
”关注我们吧!
在vue实例中,除了el、data、methods外,还存在一个叫做computed的计算属性,在计算属性中也是添加方法,但是调用的时候不用添加括号。
1
字符串操作
计算属性可以将两个字符串做拼接操作,简单的代码示例如下: <div id="app">{{fullname}}div> <script> const app = new Vue({ el:'#app', data:{ firstname:'Bear', lastname:'Mouse' }, // computed:计算属性() computed:{ fullname:function(){ return this.firstname + ' ' + this.lastname } } })script>
结果就将firstname与lastname拼接后输出了。
2
属性值的计算
利用computed计算属性对数组中对象的属性值进行计算,下面是代码示例,其中采用了三种for循环的方法对属性值计算,最后返回的值通过mustache语法显示在页面上: <div id="app">{{totalprice}}div> <script> const app = new Vue({ el:'#app', data:{ books:[ {name:'语文',price:100}, {name:'数学',price:90}, {name:'英语',price:110} ] }, // computed:计算属性() computed:{ totalprice:function(){ let finprice = 0 // 方法一 for(let i in this.books){ finprice += this.books[i].price } // 方法二 for (let book of this.books){ finprice += book.price } // 方法三 for(let i=0;i<this.books.length; i++){ finprice += this.books[i].price } return finprice } } })
3
setter和getter
在computed计算属性中定义方法时,实际上这个方法是由一个set与一个get方法组成的,但是由于set方法使用的很少,所以在computed计算属性中就常常用上一小节中的简写来写入方法,这种方法是get方法的简写。 computed:{ fullname:{ set:function(newValue){ const newname = newValue this.firstname = newname }, get:function(){ return this.firstname + ' ' + this.lastname } } }
在set方法中,必须要传入一个参数,表示使用这个参数对函数进行设定(赋值),set方法内的语句是将传入的参数进行一个保存,使得在使用get方法读取计算属性中的对象时,能够传回新设置的参数。
4
与mothods的区别
当需要重复调用某种方法但是没有变化时,computed计算属性会进行缓存,只调用一次,而methods会调用多次,相比之下,计算属性更加的高效。 END Vue之路系列文章: Vue之路 | 01-Vue安装与初体验 Vue之路 | 02-VSCODE添加Vue模板 Vue之路 | 03-插值操作与V-bind微信:熊吱
扫码关注我们
互联网知识交流平台
你的每个赞和在看,我都喜欢!