How to send data with get response from Laravel to Vue?

I want to send data from a backend route in web.php to a vue component.

Approach 1:

Route::get('/about', function () {
    return 'backend data';
})->name('about');

This works but when I refresh the page, the vue component does not get rerendered.

Approach 2:

Route::get('/about', function () {
    return view('app');
})->name('about');

This does refresh the vue component correctly but it sends the whole blade view.

I was hoping for something like this:

Route::get('/about', function () {
    return view('app')->with('backend data');
})->name('about');

which also sends the whole blade view and not the data string.

I've defined the component route in vue-router as:

{ path: "/about", name: "about", component: About },

The vue component fetches the data with axios:

onMounted(() => {
    axios.get('/about').then(res => {state.data = res.data})
})

What I want is to get the data and be able to refresh the vue component.

Upvotes: 0

Views: 773

Answers (1)

ERaufi
ERaufi

Reputation: 1663

you could do something like this

Route::get('/about', function () {
    return response()->json(['data'=>'backend data'],200);
})->name('about');

or if you want to send the view also

Route::get('/about', function () {
    return response()->view('your_view',compact('data'));
})->name('about');

Upvotes: 1

Related Questions