1 Introduction
Vue is a popular JavaScript framework for building user interfaces. In Vue, a computed property is a special property that is used to dynamically calculate new values based on changes in other data. Computed properties are one of the very important concepts in Vue application development. It can simplify code, improve performance and readability. This article will introduce in detail the concept, usage and some common application scenarios of computed properties in Vue3.
2. Basic concepts of computed properties
2.1 Definition of computed properties
In Vue, a computed property is a function that dynamically calculates a new value based on dependent data. The way computed properties are defined is computed
by creating a function in the options of the Vue component. Here is an example of a computed property:
<template>
<div>
<p>{
{ message }}</p>
<p>{
{ reversedMessage }}</p>
</div>
</template>
<script>
export default {
data() {
return {
message: 'Hello, Vue3!'
}
},
computed: {
reversedMessage() {
return this.message.split('').reverse().join('')
}
}
}
</script>
In the above code, we define a computed property that returns a new value reversedMessage
by reversing it .message
2.2 Characteristics of Computed Properties
Compared with other data binding methods, computed properties have the following characteristics:
- Cacheability : Calculated properties cache dependent data and recalculate only when the dependent data changes. If the computed property is accessed multiple times, Vue will directly return the cached result, improving performance.
- Responsive : When the data that the computed property depends on changes, it will be automatically recalculated and the view bound to the computed property will be updated.
- Readability : Computed properties allow us to write cleaner and more readable code, encapsulating complex logic in a function, improving maintainability.
3. Use of computed properties
3.1 Reading Computed Properties
In the Vue template, we can directly read the value of the calculated property, just like reading a normal property. Here's an example of reading a computed property:
<template>
<div>
<p>{
{ fullName }}</p>
</div>
</template>
<script>
export default {
data() {
return {
firstName: 'John',
lastName: 'Doe'
}
},
computed: {
fullName() {
return this.firstName + ' ' + this.lastName
}
}
}
</script>
In the above code, we define a computed property fullName
that returns firstName
the lastName
concatenation result of sum. In the template, we can {
{ fullName }}
read the value of the computed property by .
3.2 Setting of Computed Properties
In certain cases, we may wish to implement two-way binding through computed properties. In Vue3, the setting of computed properties can be achieved by adding get
and methods. set
Here's an example of setting a computed property:
<template>
<div>
<input v-model="fullName" />
</div>
</template>
<script>
export default {
data() {
return {
firstName: 'John',
lastName: 'Doe'
}
},
computed: {
fullName: {
get() {
return this.firstName + ' ' + this.lastName
},
set(value) {
const fullName = value.split(' ')
this.firstName = fullName[0]
this.lastName = fullName[1]
}
}
}
}
</script>
In the above code, we redefine the computed property fullName
and add get
the and set
method. When the value of the input box changes, set
the method update firstName
and lastName
the value will be called automatically.
4. Application Scenarios of Calculated Attributes
Computed attributes have many application scenarios in actual development. Here are a few common application scenarios.
4.1 Data filtering and sorting
Computed properties can be used to filter and sort data. For example, we have an array containing user information and want to filter users based on some criteria. We can use a computed property to dynamically compute the list of eligible users. Here is an example:
<template>
<div>
<ul>
<li v-for="user in filteredUsers" :key="user.id">
{
{ user.name }}
</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
users: [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 },
{ id: 3, name: 'Charlie', age: 35 }
],
ageThreshold: 30
}
},
computed: {
filteredUsers() {
return this.users.filter(user => user.age >= this.ageThreshold)
}
}
}
</script>
In the above code, we define a computed property filteredUsers
that ageThreshold
filters out a list of users whose age is greater than or equal to 30. In the template, v-for
a directive iterates over the list and displays the user names.
4.2 Form Validation
Computed properties can be used for form validation to determine whether a form field is valid based on different conditions. For example, we have a login form that needs to verify that the username and password meet certain requirements. We can use computed properties to dynamically calculate validation results and bind them to form error messages. Here is an example:
<template>
<div>
<input v-model="username" />
<input v-model="password" type="password" />
<p>{
{ usernameError }}</p>
<p>{
{ passwordError }}</p>
<button @click="login">Login</button>
</div>
</template>
<script>
export default {
data() {
return {
username: '',
password: '',
usernamePattern: /^[a-zA-Z0-9]{4,16}$/,
passwordPattern: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/
}
},
computed: {
usernameError() {
if (this.username === '') {
return 'Username is required'
} else if (!this.usernamePattern.test(this.username)) {
return 'Invalid username format: alphanumeric, 4-16 characters'
} else {
return ''
}
},
passwordError() {
if (this.password === '') {
return 'Password is required'
} else if (!this.passwordPattern.test(this.password)) {
return 'Invalid password format: at least 8 characters, at least 1 letter and 1 number'
} else {
return ''
}
}
},
methods: {
login() {
// Perform login logic
}
}
}
</script>
In the above code, we define two calculated properties usernameError
and passwordError
, which judge whether the requirements are met according to the value of the form field and the regular expression, and return the corresponding error message. In the template, we pass {
{ usernameError }}
and {
{ passwordError }}
display the error message. In this way, we can update the error prompt based on user input in real time, improving the interactivity and user experience of the form.
5. Summary
Computed property is one of the very useful features in Vue3. It can dynamically calculate new values based on dependent data, and has the characteristics of caching, responsiveness and readability. This article introduces the basic concept, usage and common application scenarios of computed properties. By properly applying computed properties, we can simplify code, improve performance and maintainability, and develop Vue applications more efficiently.