25.06.2018 Views

Full-Stack Vue.js 2 and Laravel 5

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Computed properties<br />

It's convenient to write logic straight into our template as an expression, for<br />

example, v-if="myExpression". But what about more complex logic that can't be<br />

defined as an expression, or simply becomes too verbose for the template?<br />

For this scenario, we use computed properties. These are properties we add to<br />

our <strong>Vue</strong> configuration that can be thought of as reactive methods which are rerun<br />

whenever a dependent value is changed.<br />

In the following example, we've declared a computed property, message, under the<br />

computed configuration section. Note the function is dependent on val, that is, the<br />

returned value of of message will be different as val changes.<br />

When this script runs, <strong>Vue</strong> will note any dependencies of message <strong>and</strong> will set up<br />

reactive binding so that, unlike a regular method, the function will be rerun<br />

whenever the dependencies change: var app = new <strong>Vue</strong>({ el: '#app',<br />

data: { val: 1 }, computed: { message() { return `The value is ${this.val}` } }<br />

});<br />

setTimeout(function() { app.val = 2; }, 2000); {{ message }} <br />

Going back to the image carousel, let's make the template terser by abstracting<br />

the expression bound to the image src into a computed property.<br />

resources/assets/<strong>js</strong>/app.<strong>js</strong>: <strong>Vue</strong>.component('image-carousel', { template: ` `, data() { ... },<br />

computed: { image() { return this.images[this.index]; } } });

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!