PASSWORD RESET

Your destination for complete Tech news

Vue

How to pass value from Laravel to Vue JS?

1.08K 0
2 min read

You can pass values from Laravel to Vue.js in several ways. Here are two common methods:

1. Pass values using props:

In your Laravel blade file, you can pass data to a Vue component as props by binding data to component tags using v-bind directive. Here is an example:

<!-- Laravel Blade File -->
<template>
  <div>
    <h1>{{ title }}</h1>
    <my-component :initial-data="{{ $data }}"></my-component>
  </div>
</template>

In this example, we are passing the Laravel $data variable to the my-component Vue component as a prop. We use the v-bind directive to bind the :initial-data prop to the $data variable. Note that we use {{ }} to output the value of $data as JSON.

In the Vue component, we can receive the prop by defining a props object in the component options:

// Vue Component
<template>
  <div>
    <p v-for="item in data">{{ item }}</p>
  </div>
</template>

<script>
export default {
  props: {
    initialData: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      data: []
    };
  },
  created() {
    this.data = this.initialData;
  }
};
</script>

In this example, we define a props object with a single initialData prop, which we expect to be an array. We then define a data property, which will hold the received prop. In the created hook, we assign the value of initialData to data.

2. Pass values using AJAX requests:

Another way to pass data from Laravel to Vue is by making AJAX requests from the Vue component to a Laravel API endpoint. In this method, you can use Laravel’s route function to generate the URL for the API endpoint. Here’s an example:

<!-- Laravel Blade File -->
<template>
  <div>
    <h1>{{ title }}</h1>
    <my-component></my-component>
  </div>
</template>

In this example, we are not passing any data to the Vue component as props. Instead, we will make an AJAX request to a Laravel API endpoint to retrieve the data.

In the Vue component, we can make an AJAX request in the created hook to retrieve the data from the Laravel API endpoint:

// Vue Component
<template>
  <div>
    <p v-for="item in data">{{ item }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      data: []
    };
  },
  created() {
    axios.get('/api/data')
      .then(response => {
        this.data = response.data;
      });
  }
};
</script>

In this example, we are using the axios library to make an AJAX request to the /api/data endpoint. We then assign the response data to the data property, which will update the component’s template to display the received data. Note that you will need to define the Laravel API endpoint in your Laravel routes file.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.