25.06.2018 Views

Full-Stack Vue.js 2 and Laravel 5

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Refactoring components to SFCs<br />

Our resource/assets/<strong>js</strong>/app.<strong>js</strong> file is almost 100 lines long now. If we keep adding<br />

components, it will start to get unmanageable, so it's time to think about splitting<br />

it up.<br />

Let's begin by refactoring our existing components to be SFCs. First, we'll create<br />

a new directory, then we will create the .vue files: $ mkdir<br />

resources/assets/components $ touch<br />

resources/assets/components/ImageCarousel.vue $ touch<br />

resources/assets/components/CarouselControl.vue<br />

Starting with ImageCarousel.vue, the first step is to create the three root elements.<br />

resources/assets/components/ImageCarousel.vue: <br />

<br />

Now, we move the template string into the template tag, <strong>and</strong> the component<br />

definition into the script tag. The component definition must be exported as a<br />

module.<br />

resources/assets/components/ImageCarousel.vue: <br />

export default { props:<br />

[ 'images' ], data() { return { index: 0 } }, computed: { image() { return<br />

this.images[this.index]; } }, methods: { changeImage(val) { let newVal =<br />

this.index + parseInt(val); if (newVal < 0) { this.index = this.images.length -1; }<br />

else if (newVal === this.images.length) { this.index = 0; } else { this.index =<br />

newVal; } } }, components: { 'carousel-control': { template: `

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

Saved successfully!

Ooh no, something went wrong!