簡體   English   中英

如何在 Vue 組件中顯示從 Laravel 資源返回的數據?

[英]How do I display data returned from Laravel resource in Vue Component?

我正在練習 Vue,對如何處理數據傳遞感到困惑。 我的 Vue 組件中有一個鏈接<a class="btn btn-success":href="'/projectpage/' + project.id">Bid</a> 感謝這個問題 在我的路線 web.php 我有這條路線Route::get('/projectpage/{id}', 'ProjectController@projectPage'); . 在我的 ProjectController 我有這個 function

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

當我返回 ProjectResource 時,它顯示 JSON 數據,當我返回視圖時,它顯示視圖和我想要顯示的數據。 但是,我想顯示來自 vue 組件的數據。 vue 組件獲取數據,然后將其顯示在刀片頁面上,例如<component></component> 我該如何 go 關於這個?

要按照您的要求進行操作,您必須使用axios 您可以通過npm install axios

接下來,檢查您的resource/js/bootstrap.js文件以確保您已導入 axios。

/**
 * 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');
}

並且,在您的resource/js/app.js文件中添加

require("./bootstrap");

運行npm run dev

最后,將腳本添加到您的 main.blade 文件<script src="{{ asset('js/app.js') }}"></script>


最后,只需從方法中通過 axios 調用

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

你的組件調用

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


讓我在下面的評論中發布。 干杯!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM