Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enhance an existing Laravel project with VueJS?

I just finished my project using only the Laravel framework. Now I want to add vue.js into my project to render the views without loading them. I went through some tutorials and found that I need to convert my blade files into Vue components to achieve this. But as I know it's a big process as some of the functions won't work in VueJS. And I don't know how to do it. Please, someone, guide me here on how to do that. Thanks in advance.

like image 801
anonymus Avatar asked Jan 31 '20 08:01

anonymus


1 Answers

  1. Rebuild your basic structure into a Vue template:
// MyTemplate.vue
<template>
  <div> <!-- keep this single "parent" div in your template -->

    <!-- your Blade layout here -->

  </div>
</template>

<script>
  export default {
    props: [ 'data' ]
  }
</script>
  1. Add your Vue template as a global component in app.js:
// app.js
import Vue from 'vue';
window.Vue = Vue;

Vue.component('my-template', require('./MyTemplate.vue').default);

const app = new Vue({
  el: '#app'
});
  1. Use this new Vue template in your Blade template as below:
<my-template :data="{{ $onePhpVarThatHoldsAllYourData }}></my-template>

Once inside the Vue template, you will not be able to reach back to your Laravel methods (e.g. @auth) or for additional data without an Ajax request, so make sure you package all the data you need in your Vue template up front. All of the data you send in will be prefixed inside the Vue template with the name of the prop you assign it to, in this case data.

  1. Convert your Blade directives to Vue directives:

Loops (e.g. @foreach) to v-fors:

@foreach ($items as $item)
  <li>{{ $item }}</li>
@endforeach

becomes

  <li v-for="item in data.items">{{ item }}</li>

Control structures (e.g. @if ($something !== $somethingElse) ... @endif) to v-ifs:

<div v-if="data.something !== data.somethingElse">
...
</div>
like image 194
Erich Avatar answered Sep 22 '22 19:09

Erich