Look at the image below and please explain where should I use computed
instead of methods
and vice versa? It confuses me.
Asked
Active
Viewed 537 times
-1
-
Does this answer your question? [Method vs Computed in Vue](https://stackoverflow.com/questions/44350862/method-vs-computed-in-vue) – hamid niakan Dec 18 '20 at 18:45
1 Answers
0
As a rule of thumb: a computed is a simple getter (though they can be setters, but that's not something you'd typically use) that is dependent on one or more properties. It'll update automatically when those properties change. You cannot pass it parameters. You would use a method when you need to pass a parameter and/or need to perform an action or mutation.
data() {
firstName: 'Bert',
lastName: 'Ernie'
},
computed: {
fullName() {
return `${this.firstName} ${this.lastName}`;
}
}
This will return "Bert Ernie" and will update automatically when either firstName
or lastName
change.
Now if you need to change something, or for example select something from a list using a parameter, you would use a method.
data() {
users: [
{ id: 1, name: 'Bert' }.
{ id: 2, name: 'Ernie' }
]
},
methods: {
getUser(userid) {
return this.users.find(user => user.id === userid);
},
setUserName(userid, newName) {
const user = this.users.find(user => user.id === userid);
if (user) {
user.name = newName;
}
}
}

Brother Woodrow
- 6,092
- 3
- 18
- 20