Getting Started with Vue.js Chapter 1
Don't forget to add a comma (,) after the closing curly bracket (}) of your
data object so Vue knows to expect a new object.
The next step is to create a function inside the computed object. One of the hardest parts of
development is naming things - make sure the name of your function is descriptive. As our
application is quite small and our manipulation basic, we'll name it messageToLower:
const app = new Vue({
el: '#app',
data: {
message: 'HelLO Vue!'
},
computed: {
messageToLower() {
return 'hello vue!';
}
}
});
In the preceding example, I've set it to return a hardcoded string, which is a lowercased
version of the contents of the message variable. Computed functions can be used exactly as
you would use a data key in the view. Update the view to output {{ messageToLower }}
instead of {{ message }} and view the result in your browser.
There are a few issues with this code, however. Firstly, if the value of messageToLower
was being hardcoded, we could have just added it to another data property. Secondly, if the
value of message changes, the lowercase version will now be incorrect.
Within the Vue instance, we are able to access both data values and computed values using
the this variable - we'll update the function to use the existing message value:
computed: {
messageToLower() {
return this.message.toLowerCase();
}
}
The messageToLower function now references the existing message variable and, using a
native JavaScript function, converts the string to lower case. Try updating the message
variable in your application, or in the JavaScript console, to see it update.