How to use vue.js component in laravel blade?

Member

by larissa , in category: PHP Frameworks , 9 months ago

How to use vue.js component in laravel blade?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adan , 5 months ago

@larissa 

To use a Vue.js component in a Laravel Blade template, you can follow these steps:

  1. Install Vue.js dependencies: Run npm install vue to install Vue.js.
  2. Create the Vue component: Create a new Vue component in a JavaScript file, for example MyComponent.vue.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// MyComponent.vue
<template>
  <div>
    <h1>{{ message }}</h1>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: 'Hello from Vue component!'
    };
  }
};
</script>


  1. Compile the Vue component: Run npm run dev or npm run watch to compile the component.
  2. Include the compiled Vue component: Include the compiled Vue component in your Laravel Blade template.
1
2
3
4
5
6
// YourBladeTemplate.blade.php
<div id="app">
   <my-component></my-component>
</div>

<script src="{{ mix('js/app.js') }}"></script>


  1. Initialize the Vue instance: Initialize the Vue instance in your app.js file.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// app.js
import Vue from 'vue';
import MyComponent from './components/MyComponent.vue';

new Vue({
   el: '#app',
   components: {
      'my-component': MyComponent
   }
});


  1. Run the Laravel server: Run php artisan serve to start the Laravel server.


Now, you should be able to see the Vue.js component rendered in your Laravel Blade template.


Note: Make sure to compile the Vue component whenever you make changes to it, and don't forget to include the necessary JavaScript files in your Blade template.