#In this article, we will introduce you to the computed properties in Vue through specific examples.
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 + ' '+ 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+' '+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!