0

I am practicing Vue and am confused on how to handle data passing. I have a link in my Vue component <a class="btn btn-success" :href="'/projectpage/' + project.id">Bid</a> Thanks to this question. In my routes web.php I have this route Route::get('/projectpage/{id}', 'ProjectController@projectPage');. In my ProjectController I have this function

    public function projectPage($id){
       $project = Project::findOrFail($id);
       // return new ProjectResource($project);
       return view('project',['project'=>$project]);
}

When I return the ProjectResource it displays the JSON Data and when I return the view, it displays the view and the data that I want to be displayed. I however want to display the data from a vue component. The vue component to fetch the data and then display it on the blade page say like <component></component>. How do I go about this?

davidkihara
  • 493
  • 1
  • 10
  • 30

1 Answers1

0

To do what you are asking, you will have to use axios. You can install it by npm install axios

Next, check your resource/js/bootstrap.js file to make sure you have axios imported.

/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

/**
 * Next we will register the CSRF Token as a common header with Axios so that
 * all outgoing HTTP requests automatically have it attached. This is just
 * a simple convenience so we don't have to attach every token manually.
 */

let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

And, in your resource/js/app.js file add

require("./bootstrap");

Run npm run dev

Finally, add the script to your main .blade file <script src="{{ asset('js/app.js') }}"></script>


At the end, simply call via axios from a method

axios.get('route')
     .then(response => {
          console.log(response.data); // store this in a variable
      })
      .catch(error => {
          console.log(error.response.data);
      });

Your component call

<YourComponent v-for="list in lists" />


Keep me posted in the comments below. Cheers!

Digvijay
  • 7,836
  • 3
  • 32
  • 53
  • I have done this and am getting the json data but its not rendering in the component. Its not a list, its just a single project – davidkihara Jun 17 '20 at 05:18