Skip to content

Instantly share code, notes, and snippets.

@jackmcdade
Created August 10, 2016 20:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jackmcdade/9b88f6cb1e11bab6aeefdb078fba9d83 to your computer and use it in GitHub Desktop.
Save jackmcdade/9b88f6cb1e11bab6aeefdb078fba9d83 to your computer and use it in GitHub Desktop.
Vue/Laravel Server Side Preloading
<script>
export default {
props: {
endpoint: {
type: [String, Boolean],
default: false
},
preloaded: {
type: Boolean,
default: false
}
},
data() {
return {
loading: true,
items: []
}
},
methods: {
hydrate() {
(this.endpoint) ? this.hydrateFromEndpoint() : this.hydrateFromPreload();
this.loading = false;
},
hydrateFromEndpoint() {
this.$http.get(this.endpoint).then(function (response) {
this.items = response.data
});
},
hydrateFromPreload() {
this.items = preload;
}
},
ready() {
this.hydrate()
}
}
</script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script>var preload = @yield('preload', 'false')</script>
</head>
<body id="app">
@yield('body')
<script src="/js/app.js"></script>
</body>
</html>
<script>
export default {
mixins: [Hydratable]
}
</script>
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class RandomController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$noun = factory(\App\Noun::class, 25)->make();
return view('screen')->withNoun($noun);
}
}
@extends('layout')
@section('preload', $noun)
@section('content')
<div class="container">
<!-- Hydrate with preloaded data -->
<nifty preload="true" v-cloak inline-template>
<table>
<tr v-for="item in items">
<td>@{{ item.name }}</td>
<td>@{{ item.description }}</td>
</tr>
</table>
</nifty>
<!-- Hydrade with an API endpoint -->
<nifty endpoint="/api/random" v-cloak inline-template>
<table>
<tr v-for="item in items">
<td>@{{ item.name }}</td>
<td>@{{ item.description }}</td>
</tr>
</table>
</nifty>
</div>
@endsection
@jackmcdade
Copy link
Author

This preload/hydratable approach will let you set data in your Controller, inject it into Vue.js, and let you write super thin Vue components that can consume data either from an API endpoint or from the server-side rendered data for speed (my favorite).

It's kinda cool. I dig it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment