Complete Vue.js 2 Web Development_ Practical guide to building end-to-end web development solutions with Vue.js 2

(singke) #1
Getting Started with Vue.js Chapter 1

Computed values


The data object in Vue is great for storing and retrieving data directly, however, there may


be times where you want to manipulate the data before outputting it in your applications.


We can do that using the computed object in Vue. Using this technique, we are able to start


adhering to the MVVM (Model-View-ViewModel) methodology.


MVVM is a software architectural pattern where you separate out various parts of your
application into distinct sections. The Model (or data) is your raw data input - be it from an


API, database, or hardcoded data values. In the context of Vue, this is typically the data


object we used earlier.


The view is the frontend of your application. This should just be used for outputting the


data from the Model, and should not contain any logic or data manipulation, with the
exception of some unavoidable if statements. For the Vue applications, this is all the code


placed within the

tags.


The ViewModel is the bridge between the two. It allows you to manipulate the data from
the Model before it is output by the view. Examples of this could range from changing a


string to uppercase or prefixing a currency symbol, up to filtering out discounted products


from a list or calculating the total value of a field across an array. In Vue, this is where the
computed object comes in.


The computed object can have as many properties as required - however, they must be


functions. These functions can utilize data already on the Vue instance and return a value,


be it a string, number, or array that can then be used in the view.


The first step is to create a computed object within our Vue application. In this example, we


are going to use a computed value to convert our string to lowercase, so set the value of
message back to a string:


const app = new Vue({
el: '#app',

data: {
message: 'Hello Vue!'
},
computed: {
}
});
Free download pdf