Home  >  Article  >  Web Front-end  >  What are vue.js computed properties? (code example)

What are vue.js computed properties? (code example)

藏色散人
藏色散人Original
2019-04-25 14:13:402811browse


#In this article, we will introduce you to the computed properties in Vue through specific examples.

What are vue.js computed properties? (code example)

What is a computed property?

Computed properties look like data properties in Vue. But we can perform some arithmetic and non-arithmetic tasks.

<template>
  <ul>
   <li>First name : {{firstName}}</li>
   <li>Last name : {{lastName}}</li>
   <li>Full name : {{firstName + &#39; &#39;+ lastName}}</li>
  </ul>
</template>

<script>
 data:function(){
     return{
         firstName: "Sai",
         lastName: "Gowtham"
     }
 }
</script>

In the above code, we create two data attributes firstName and lastName and insert them into the template.

If you look at our template, we added the Full Name logic inside {{}} curly braces.

Example

Example of how to create your first computed property.

Computed properties are declared in the computed property object.

<template>
  <ul>
   <li>First name : {{firstName}}</li>
   <li>Last name : {{lastName}}</li>
   <!-- 计算属性 -->
   <li>Full name : {{fullName}}</li>
  </ul>
</template>

<script>
export default{
     data:function(){
     return{
         firstName: "Sai",
         lastName: "Gowtham"
     }
  },
  computed:{
      fullName:function(){
          return this.firstName+&#39; &#39;+this.lastName
      }
  }
}

Here we add a computed property called fullName, which is a function that returns the user's full name.

We can use calculated properties in templates just like data properties.

Computed properties are cached by vue, so it only re-evaluates the logic when the underlying data property changes, which means if firstName or lastName has not changed, then it only returns the previously calculated result without running the function again.

Related recommendations: "javascript tutorial"


The above is the detailed content of What are vue.js computed properties? (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn