3

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?

1 Answer 1

9

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')
})
Sign up to request clarification or add additional context in comments.

3 Comments

instead of passing #mount-node to $mount() I think it would be better to pass mountNode element
Glad this helped you out :)
Where was Toast declared/set so that you could access it in the event listener?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.