Skip to content

Instantly share code, notes, and snippets.

@sinri
Created October 30, 2018 08:54
Show Gist options
  • Save sinri/d2c602fbc93d8eb08dcde582ddedac62 to your computer and use it in GitHub Desktop.
Save sinri/d2c602fbc93d8eb08dcde582ddedac62 to your computer and use it in GitHub Desktop.
Live Vue Template Component for Vue.js
// Live Vue Template
// Author: Sinri Edogawa
//
// Original Inspire:
// https://github.com/cheng-kang/wildfire/blob/96c8698c336c0d6d022e80ea50948aed2c0352a6/src/components/WfMarkedContent.vue
// and usage https://github.com/cheng-kang/wildfire/blob/96c8698c336c0d6d022e80ea50948aed2c0352a6/src/components/WfCommentCard.vue
//
// but I cannot replay this ... until I added one WATCH, as initial compile is too early
//
// Sample Usage:
// Vue.component("contract_preview_anonymous",contract_preview_anonymous);
// <contract_preview_anonymous :content="test" :params="sampleParams"></contract_preview_anonymous>
let contract_preview_anonymous = {
name: 'contract_preview_anonymous',
template:'<div ref="preview_container"></div>',
props: [
'content',
'params',
],
watch:{
// This is important if your content might change after compile.
content:function (newContent,oldContent) {
console.log('content watched changing',newContent,oldContent);
this.$refs['preview_container'].innerHTML='';
this.compile();
}
},
mounted () {
this.compile();
},
methods: {
compile () {
// Here `html` is a string serving as Vue Template,
// i.e. it may contain v-if, :bind, @click and so on.
const html = this.content;
const params=this.params;
// Here generate a vue component generator,
// but not register.
const Component = Vue.extend({
// The template given by user might not safe in single root
// so add a container around it
// template: `<div> ${html} </div>`,
template: '<div> '+html+' </div>',
data:function(){
return {
params:params
}
},
// Here you may write more, mount的, updated, watch, computed, etc.
});
// Use component generator to create instance to DOM, but not mounted yet
const tempComponent = new Component().$mount();
// Mount the generated to its wanted parent
this.$refs['preview_container'].appendChild(tempComponent.$el)
}
}
// Actually, this component is not a child component of any components.
// It is a dynamically generated anonymous component, and inserted in the target place.
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment