Get Off My Lawn
Get Off My Lawn

Reputation: 36351

Vue: Append component to element

I have a vue component that looks like this:

<template>
  <div class="toast" role="alert" aria-live="assertive" aria-atomic="true" data-autohide="true" data-delay="5000">
    <!-- HTML Clipped -->
    <div class="toast-body">{{message}}</div>
  </div>
</template>

<script>
export default {
  props: ['title', 'message']
}
</script>

I then have an eventListener that listens for messages sent via postMessage. This does work, but I don't think mount is the correct way to do what I want.

window.addEventListener('message', e => {
  let toastComp = Vue.extend(Toast)
  let toast = new toastComp({
    propsData: {
      message: 'hello'
    }
  }).$mount('.toast-container')
})

What I am looking for, is for vue to append the component to the .toast-container element instead of replacing the element. How can this be done?

Upvotes: 3

Views: 14084

Answers (1)

Steve Holgado
Steve Holgado

Reputation: 12089

How about creating and appending an element inside of .toast-container and then mounting your component on to that new element:

window.addEventListener('message', e => {
  const toastContainer = document.querySelector('.toast-container')
  const mountNode = document.createElement('div')
  mountNode.id = 'mount-node'
  toastContainer.appendChild(mountNode)

  let toastComp = Vue.extend(Toast)
  let toast = new toastComp({
    propsData: {
      message: 'hello'
    }
  }).$mount('#mount-node')
})

Upvotes: 9

Related Questions