Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject or Initialize Vue components in generated HTML

I use a an WYSIWYG article editor that generates some HTML for articles that I save in the database and later show to the user.

The problem is I need to insert Vue components into this auto generated HTML for showing dynamic products. I can make a custom block in the editor that adds in HTML but I want it to work as a Vue component that updates the product description directly from the database.

What Im thinking now is to add a button that adds a div with a data property of the products ID. I can then replace that div in the code with a Vue component with the same ID by injecting a component.

Another idea I had was to simply add in components like <product id="1031"/> as plain html and then try to compile the whole article HTML with Vue but I read that the v-html directive only compile code as plain HTML.

Is this possible? Or is there any better ideas?

like image 618
nilsi Avatar asked Oct 28 '25 21:10

nilsi


1 Answers

If you are using the full build of Vue (not the runtime only build) you can initialize a new instance of Vue and mount it wherever you like, pass in data etc.

// Main app        
new Vue({
  el: '#app',
  data: {
    stuff: 'inserted message'
  },
  methods: {
    clicked() {
      // Add new
      new Vue({
        template: `<h1 style="color: red;">{{ message }}</h1>`,
        parent: this,
        data: {
          message: 'new message'
        }
      }).$mount(document.getElementById('more'))
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.js"></script>
<div id="app">
  There are some things here before like {{ stuff }}
  but when you press <button @click="clicked()">add more</button>
  you can add more things here:
  <div id="more"></div>
</div>
like image 150
Amrit Kahlon Avatar answered Oct 31 '25 12:10

Amrit Kahlon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!