1. 程式人生 > 其它 >計算屬性體驗(computed)

計算屬性體驗(computed)

技術標籤:vuevue

計算屬性體驗(computed)

計算屬性是一個屬性,呼叫該屬性不用加()

<body>
<div id="app">
  <h2>{{firstName+' '+lastName}}</h2>
  <h2>{{getFullName()}}</h2>
  <h2>{{fullName}}</h2>

</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> </body>

在這裡插入圖片描述

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>計算屬性的複雜操作</title>
</head>
<body>
<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: 'js高階程式設計', price: 96}, {id: 111, name: '你所不知道的javascript', price: 50}, {id: 112, name: 'js資料結構', price: 32}, {id: 113, name: 'DOM程式設計藝術', price: 57}, ], }, computed: { totalPrice: function () { let result = 0; for (let i = 0; i < this.books.length; i++) { result += this.books[i].price; } return result; } } }); </script> </body> </html>

在這裡插入圖片描述