04计算属性

计算属性

什么是计算属性

模板内的表达式非常便利,但是设计它们的初衷是用于简单运算的。在模板中放入太多的逻辑会让模板过重且难以维护。

计算属性的用法

在一个计算属性里可以完成各种复杂的逻辑,包括运算、函数调用等,只要最终返回一个结果就可以。

<div id="app">
	<h2>{{firstName+' '+lastName}}</h2>
    <h2>{{fullName}}</h2>
    <h2>总价格:{{totalPrice}}</h2>
</div>

<body>
	<script src="../js/vue.js"></script>
	<script>
		const app = new Vue({
			el: "#app",
			data: {
				firstName:"luo",
        lastName:"yichen",
        books:[
          {id:100, name: 'java核心技术' , price:100},
          {id:101, name: 'c核心技术' , price:100},
          {id:102, name: 'php核心技术' , price:100},
          {id:103, name: 'python核心技术' , price:100}
        ]
			},
      // computed: 计算属性()
      computed:{
        fullName:function(){
          return this.firstName+' '+this.lastName
        },
        totalPrice:function(){
          let result =0
          for (let i=0;i < this.books.length; i++){
            result += this.books[i].price
          }
          return result;
        }
      }
		})
	</script>

计算属性的getter和setter

每个计算属性都包含一个getter和一个setter

  • 在上面的例子中,我们只是使用getter来读取。
  • 在某些情况下,你也可以提供一个setter方法 (不常用)。
  • 在需要写setter的时候,代码如下:
<div id="app">
 <h2>{{fullName}}</h2>
</div>

<body>
 <script src="../js/vue.js"></script>
 <script>
   const app = new Vue({
     el: "#app",
     data: {
       firstName: "luo",
       lastName: "yichen",
     },
     computed: {
       // fullName: function () {
       //   return this.firstName + ' ' + this.lastName
       // }
       // 计算属性一般没有set值,只读属性。
       fullName:{
         set: function(newValue){
           const names = newValue.split(" ");
           this.firstName = names[0];
           this.lastName = names[1];
         }, 
         get: function(){
           return this.firstName + ' ' + this.lastName
         }
       },
       // 简洁写法
       // fullName:function(){
       //   return this.firstName+' '+this.lastName
       // }
     }
   })
 </script>
</body>

计算属性与methods对比

<div id="app">
  <!-- 通过拼接:语法过于繁琐 -->
  <h2>{{firstName}} {{lastName}}</h2>
  <!-- 通过定义methods 每次都要调用-->
  <h2>{{getFullName()}}</h2>
  <!-- 通过computed 如果没有发生改变只需要调用一次-->
  <h2>{{fullName}}</h2>
</div>

<body>
  <script src="../js/vue.js"></script>
  <script>
    const app = new Vue({
      el: "#app",
      data: {
        firstName: "luo",
        lastName: "yichen"
      },
      methods: {
        getFullName: function () {
          return this.firstName + ' ' + this.lastName
        }
      },
      computed: {
        fullName: function () {
          return this.firstName + ' ' + this.lastName
        }
      }
    })
  </script>
</body>

posted @ 2021-11-08 22:47  天亮說晚安  阅读(33)  评论(0)    收藏  举报