计算属性

计算属性的基本使用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">
    <!--使用计算属性,不需要加小括号-->
    <h2>{{fullName}}</h2>
</div>

<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
      el:'#app',
      data:{
          firstName: 'Zhang',
          lastName: 'San'
      },
      //计算属性
      computed: {
        fullName: function () {
            return this.firstName + ' ' + this.lastName;
        }
      }
    })
</script>
</body>
</html>

  

计算属性的复杂操作

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">
    <h2>总价格:{{totalPrice}}</h2>
    <h2>总价格:{{totalPrice1}}</h2>
</div>

<script src="../js/vue.js"></script>
<script>
  const app = new Vue({
      el:'#app',
      data:{
          books: [
              {id: 110,name: 'vue',price: 119},
              {id: 111,name: 'java',price: 100},
              {id: 112,name: 'python',price: 90},
          ]
      },
      computed: {
          totalPrice: function () {
              let result = 0;
              for (let i = 0; i < this.books.length; i++) {
                  result += this.books[i].price;
              }
              return result;
          },
          totalPrice1: function () {
              let result = 0;
              for (let book of this.books) {
                  result += book.price;
              }
              return result;
          }
      }
    })
</script>
</body>
</html>

  

 

posted @ 2021-08-15 16:28  Mr_sven  阅读(358)  评论(0编辑  收藏  举报