Vue.js 2 Design Patterns and Best Practices
上QQ阅读APP看书,第一时间看更新

Watched properties

Computed properties are not always the answer to our reactive data problems, sometimes we need to create our own custom watched properties. Computed properties can only be synchronous, must be pure (for example, no observed side-effects), and return a value; this is in direct contrast to a watched property, which is often used to deal with asynchronous data.

A watched property allows us to reactively execute a function whenever a piece of data changes. This means that we can call a function every time an item from our data object changes, and we'll have access to this changed value as a parameter. Let's take a look at this with a simple example:

Note: Axios is a library that will need to be added to the project. To do so, head to https://github.com/axios/axios and follow the installation steps provided.
<template>
<div>
<input type="number" v-model="id" />
<p>Name: {{user.name}}</p>
<p>Email: {{user.email}}</p>
<p>Id: {{user.id}}</p>
</div>
</template>

<script>
import axios from 'axios';

export default {
data() {
return {
id: '',
user: {}
}
},
methods: {
getDataForUser() {
axios.get(`https://jsonplaceholder.typicode.com/users/${this.id}`)
.then(res => this.user = res.data);
}
},
watch: {
id() {
this.getDataForUser();
}
}
}
</script>

In this example, any time our text box changes with a new id (1-10), we get information about that particular user, like so:

This is effectively watching for any changes on the id and calling the getDataForUser method, retrieving new data about this user.

Although watched properties do have a lot of power, the benefits of computed properties on performance and ease of use should not be understated; therefore wherever possible, favor computed properties over watched properties.