预览模式: 普通 | 列表

vue2实现Teleport,用来做跨组件DOM挂载

 父组件调用:(to="#app"的意思是把#divPopup挂载到#app节点上

Javascript代码
  1. <Teleport to="#app">  
  2.         <div id="divPopup" style="z-index:20000;" v-show="dialogVisible">  
  3.           <el-button @click="clickH1">yes</el-button>  
  4.           <el-button @click="clickH2">no</el-button>  
  5.         </div>  
  6. </Teleport>  

子组件:

Javascript代码
  1. <script>  
  2.     export default {  
  3.         name: 'teleport',  
  4.         props: {  
  5.             /* 移动至哪个标签内,最好使用id */  
  6.             to: {  
  7.                 type: String,  
  8.                 required: true  
  9.             }  
  10.         },  
  11.   
  12.         mounted() {  
  13.             document.querySelector(this.to).appendChild(this.$el)  
  14.         },  
  15.   
  16.         destroyed() {  
  17.             document.querySelector(this.to).removeChild(this.$el)  
  18.         },  
  19.   
  20.         render() {  
  21.             return <div>{this.$scopedSlots.default()}</div>  
  22.         }  
  23.     }  
  24. </script>  

 

分类:前端研究 | 固定链接 | 评论: 0 | 引用: 0 | 查看次数: 2967