Computed Properties
While it is possible to use in-template expression, they can get messy and they are not reusable. This is where a computed property comes in. Computed properties are functions inside to computed property of the data object.
In the example below, the computed property, randomLink
, will return a link from the links array at random.
const app = new Vue({
el: '#app',
data: {
links: [
'http://youtube.com',
'http://en.wikipedia.org',
'http://facebook.com',
'http://twitter.com',
'http://amazon.com',
'http://imdb.com',
'http://reddit.com',
'http://pinterest.com',
'http://ebay.com',
'http://tripadvisor.com'
]
},
computed: {
randomLink: function () {
return this.links[Math.floor(Math.random() * this.links.length)]
}
}
})
You can data-bind to computed properties in templates just like normal properties. So our randomLink
computed property can be bound to the href of a link.
<a :href="randomLink">Random link</a>
Vue is aware of the any dependencies of a computed property and will update any binding if the dependencies. So, if our array links would be altered a new randomLink will be chosen.
In the example below, each time a random link is clicked, it is removed the link from the links array. Because the links array is a dependency of our computed property, vue will trigger a new random link to be selected.
<a :href="randomLink" @click="remove(randomLink)">Random Link</a>
const app = new Vue({
el: '#app',
data: {
links: [
'http://youtube.com',
'http://en.wikipedia.org',
'http://facebook.com',
'http://twitter.com',
'http://amazon.com',
'http://imdb.com',
'http://reddit.com',
'http://pinterest.com',
'http://ebay.com',
'http://tripadvisor.com'
]
},
methods: {
remove: function (link) {
this.links.splice(this.links.indexOf(link), 1)
}
},
computed: {
randomLink: function () {
return this.links[Math.floor(Math.random() * this.links.length)]
}
}
})