How to pass html template as props to Vue component

前端 未结 3 2098
时光取名叫无心
时光取名叫无心 2021-01-06 01:28

I have a textarea component that include html tag and I want to get html in edit mode in this component. I use Laravel to

3条回答
  •  别那么骄傲
    2021-01-06 01:54

    In both alternatives...

    The usage of the my-component stays the same:

    
       

    hello world


    Full working demo:

    Vue.component('my-component', {
      props: ["content", "name", "id"],
      template: `
          
    `, data() { return {valueForMyTextArea: '', myContent: null} } }); Vue.component('textarea-slot', { props: ["value", "name", "id"], render: function(createElement) { return createElement("textarea", {attrs: {id: this.$props.id, name: this.$props.name}, on: {...this.$listeners, input: (e) => this.$emit('input', e.target.value)}, domProps: {"value": this.$props.value}}, [createElement("template", {ref: "slotHtmlRef"}, this.$slots.default)] ); }, data() { return {defaultSlotHtml: null} }, mounted() { this.$emit('input', [...this.$refs.slotHtmlRef.childNodes].map(n => n.outerHTML).join('\n')) } }); Vue.component('vnode-to-html', { props: ['vnode'], render(createElement) { return createElement("template", [this.vnode]); }, mounted() { this.$emit('html', [...this.$el.childNodes].map(n => n.outerHTML).join('\n')); } }); new Vue({ el: '#app' })
    
    
    

    hell o world1

    hello world2

    Breakdown:

    • Vue parses the s into VNodes and makes them available in the this.$slots.SLOTNAME property. The default slot, naturally, goes in this.$slots.default.
    • So, in runtime, you have available to you what has been passed via (as VNodes in this.$slots.default). The challenge now becomes how to convert those VNodes to HTML String? This is a complicated, still open, issue, which may get a different solution in the future, but, even if it ever does, it will most likely take a while.
    • Both solutions above (template-slot and vnode-to-html) use Vue's render function to render the VNodes to the DOM, then picks up the rendered HTML.
    • Since the supplied slots may have arbitrary HTML, we render the VNodes into an HTML Template Element, which doesn't execute any
提交回复
热议问题