Skip to content

Instantly share code, notes, and snippets.

@pi0
Last active August 20, 2020 00:57
Show Gist options
  • Save pi0/13d221b51f9eb48bec140e78966f2606 to your computer and use it in GitHub Desktop.
Save pi0/13d221b51f9eb48bec140e78966f2606 to your computer and use it in GitHub Desktop.
Vue Universal Runtime Compile
<template>
<div>
<component :is="CMSComponent" :x="x" />
<button @click="x++">
Click on me
</button>
</div>
</template>
<script>
import compile from '~/compile'
export default {
fetch () {
this.cmsContent = `
<div :class="['test']">
Clicked: {{ x }} times
</div>
`
},
data () {
return {
x: 0,
cmsContent: 'loading...'
}
},
computed: {
CMSComponent () {
return compile(this.cmsContent, { props: ['x'] })
}
}
}
</script>
let _compile
const _cache = {}
if (process.client) {
_compile = (template) => {
const Vue = require('vue/dist/vue.common')
return Vue.compile(template).render
}
} else {
_compile = (template) => {
const compiler = require('vue-template-compiler')
return compiler.ssrCompileToFunctions(template).render
}
}
export default function compile (template, additional) {
const render = _cache[template] = _cache[template] || _compile(template)
return { ...additional, render }
}
<template>
<div>
<CustomComponent foo="bar" />
</div>
</template>
<script>
import compile from '~/compile'
const CustomComponent = compile('<span>{{ foo }}</span>', { props: ['foo'] })
export default {
components: {
CustomComponent
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment