vue中计算属性computed

    科技2026-01-09  12

    简单的案例:将firstName和lastName结合起来并且中间还要加上空格

    <div id="app"> <!-- 计算属性的作用是当要对输出的内容加以修改之后才输出的--> <!-- 如果将firstName和lastName结合起来并且中间还要加上空格的话--> <h2>{{firstName+' '+lastName}}</h2> <h2>{{firstName}} {{lastName}}</h2> <h2>{{getFullName()}}</h2> <!-- 运用计算属性来显示的时候不需要加上()--> <h2>{{fullName}}</h2> F </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { firstName:'lebron', lastName:'james' }, // 这个就是计算属性,里面也是定义的函数,起名字的时候尽量要按照属性的格式来起名字 computed:{ fullName:function () { return this.firstName+' '+this.lastName } }, methods:{ getFullName:function () { return this.firstName+' '+this.lastName } } }) </script> 复杂的案例:将数组books中的price拿出来并且输出综=总和的值 <div id="app"> <h2>书的总价格:{{totalPrice}}</h2> </div> <script src="../js/vue.js"></script> <script> const app = new Vue({ el: '#app', data: { books:[ {id:110, name:'编程艺术',price:119}, {id:111, name:'代码大全',price:105}, {id:112, name:'深入理解计算机原理',price:99}, {id:113, name:'现代操作系统',price:89}, ] }, // 计算属性有缓存 computed:{ totalPrice:function () { let total=0; for(let i=0;i<this.books.length;i++){ total+=this.books[i].price } return total; /* ES6中的表示方法: for(let i in this.books){ this.books[i] }或者 for(let book of this.books){ }*/ } } }) </script>
    Processed: 0.017, SQL: 9