Last active
September 13, 2020 07:50
-
-
Save sebastianrothbucher/e093751f5ba89b08a163b5fd13c506fb to your computer and use it in GitHub Desktop.
Quick SSR test drive (thx, https://ssr.vuejs.org/)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// "isomorphic-fetch": "^2.2.1", | |
// "vue": "^2.6.10", | |
// "vue-server-renderer": "^2.6.10" | |
require('isomorphic-fetch'); | |
// Step 1: Create a Vue instance | |
const Vue = require('vue') | |
Vue.component('my-component', { | |
template: `<div>Hello World {{msg}}</div>`, | |
data() { | |
return {msg: null} | |
}, | |
mounted() { | |
return fetch('http://localhost:8080/data.json') | |
.then(res => res.json()) | |
.then(res => this.msg = res.msg) | |
}, | |
serverPrefetch() { // !!! | |
return fetch('http://localhost:8080/data.json') | |
.then(res => res.json()) | |
.then(res => this.msg = res.msg) | |
}, | |
}) | |
const app = new Vue({ | |
template: `<div id="app"><my-component/></div>`, | |
}) | |
// Step 2: Create a renderer | |
const renderer = require('vue-server-renderer').createRenderer() | |
// Step 3: Render the Vue instance to HTML | |
// in 2.5.0+, returns a Promise if no callback is passed: | |
renderer.renderToString(app) | |
.then(html => console.log(html)) | |
.catch(err => console.error(err)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment