简体   繁体   中英

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?

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')
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM