How to pass data from Laravel to Vue.js components



Image not found!!

Passing data from Laravel to Vue.js components can be done in a few different ways. Here are two common methods:

1. Using Props

In your Blade view file (e.g., resources/views/example.blade.php):

html
<!DOCTYPE html> <html> <head> <!-- Include Vue.js library --> <script src="https://cdn.jsdelivr.net/npm/vue@2"></script> </head> <body> <div id="app"> <!-- Pass data to Vue component using props --> <example-component :initial-data="{{ json_encode($someData) }}"></example-component> </div> <!-- Include your compiled Vue component --> <script src="{{ mix('js/app.js') }}"></script> </body> </html>

In your Vue component file (e.g., resources/js/components/ExampleComponent.vue):

html
<template> <div> <p>{{ receivedData }}</p> </div> </template> <script> export default { props: ['initialData'], data() { return { receivedData: this.initialData }; } } </script>

2. Using Inline Template

In your Blade view file (e.g., resources/views/example.blade.php):

html
<!DOCTYPE html> <html> <head> <!-- Include Vue.js library --> <script src="https://cdn.jsdelivr.net/npm/vue@2"></script> </head> <body> <div id="app"> <!-- Use inline template and pass data directly --> <example-component inline-template :initial-data="{{ json_encode($someData) }}"></example-component> </div> <!-- Include your compiled Vue component --> <script src="{{ mix('js/app.js') }}"></script> </body> </html>

In your Vue component file (e.g., resources/js/components/ExampleComponent.vue):

html
<script> export default { data() { return { receivedData: this.$options.propsData.initialData }; } } </script>

In both methods, make sure to compile your Vue component using a tool like Laravel Mix. You can run npm run dev or npm run watch to compile your assets. This will generate the necessary JavaScript file (e.g., public/js/app.js) that you included in your Blade view file. Adjust the paths and filenames based on your project structure.