简体   繁体   English

Vue:将组件附加到元素

[英]Vue: Append component to element

I have a vue component that looks like this: 我有一个Vue组件,看起来像这样:

<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 . 然后,我有一个eventListener,它侦听通过postMessage发送的消息。 This does work, but I don't think mount is the correct way to do what I want. 这确实有效,但是我认为mount是执行我想要的正确方法。

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. 我正在寻找的是.toast-container将组件附加到.toast-container元素,而不是替换该元素。 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: 如何在.toast-container内部创建和附加元素,然后将组件安装到该新元素上, .toast-container

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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