计算属性(computed)的基本使用

在这里插入图片描述

1、计算属性的基本使用

<body>
<div id="app">
  <h2>{
   
   {getFullName()}}</h2>
  <h2>{
   
   {fullName}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
      
      
        el: '#app',
        data: {
      
      
          message:'你好呀',
          firstName: 'Lebron',
          lastName: 'James'
        },
      //computed:计算属性
      computed: {
      
      
          fullName: function () {
      
      
            return this.firstName +' '+ this.lastName
          }
      },
      methods: {
      
      
        getFullName() {
      
      
          return this.firstName +' '+ this.lastName
        }
      }

    })
</script>
</body>

在这里插入图片描述

2、计算属性的复杂使用

<body>
<div id="app">
  <h2>总价格:{
   
   {totalPrice}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
    const app = new Vue({
      
      
      el: '#app',
      data: {
      
      
        message:'你好呀',
        books:[
          {
      
      id:101,name:'Unix编程大全',price:79},
          {
      
      id:102,name:'代码大全',price:96},
          {
      
      id:103,name:'深入理解计算机原理',price:99},
          {
      
      id:104,name:'现代操作系统',price:88},
        ]
      },
      computed:{
      
      
        totalPrice:function() {
      
      
          let result = 0
          for(let i = 0;i<this.books.length;i++){
      
      
            result +=this.books[i].price
          }
          return result
        }
      }
    })
</script>
</body>

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_46112274/article/details/121111615
今日推荐