如何使用vue2将DOM元素移动到特定节点位置?

2026-05-22 10:342阅读0评论SEO资源
  • 内容介绍
  • 文章标签
  • 相关推荐

本文共计417个文字,预计阅读时间需要2分钟。

如何使用vue2将DOM元素移动到特定节点位置?

背景:在编写商城页面时,PC端的布局图是按照宽度1920设计的,内部内容区域(main)宽度为1191px,写死的指定宽度。

如何使用vue2将DOM元素移动到特定节点位置?

新页面:随后出现了一个页面,类似于12306的页面,图片部分直接占满了屏幕。

背景:在写商城页面时,PC端给的设计图纸是按照宽度1920给的,内部内容区域(main)1191px,写死的指定宽度。然后新出了一个页面,类似于12306的这个页面,图片部分,直接占满了屏幕的100vw,内部div的宽度,超出了外部的,因此想到了vue3新出的teleport,vue2如何实现这个功能


新建一个teleport组件

点击查看代码

<script> export default { name: 'teleport', props: { /* 移动至哪个标签内,最好使用id */ to: { type: String, required: true } }, mounted() { document.querySelector(this.to).appendChild(this.$el) }, destroyed() { document.querySelector(this.to).removeChild(this.$el) }, render() { return <div>{this.$scopedSlots.default()}</div> } } </script>

从使用页面引入组件
点击查看代码

<template> <div class="logisticsInfo"> <div class="title-box"> <teleport to="#header__center"> <img src="../assets/logisticsInfoImgs/bg-title.png" alt="" class="bg-box"></teleport> </div> </div> </template> <script> import teleport from './components/teleport.vue' export default { name: 'QsMallWebLogisticsInfo', components: { teleport, }, data() { return {} }, mounted() {}, methods: {}, } </script> <style lang="scss" scoped> .logisticsInfo { .title-box { } } </style> <style lang="scss"> #header__center { .bg-box { height: 458px; width: 100%; } } </style>

注意样式不要写在使用属性里 指定转移的节点,通过id的方式,进行绑定
点击查看代码

<div id="header__center"></div> <div class="main"> <router-view ref="mallPage"></router-view> </div>

本文共计417个文字,预计阅读时间需要2分钟。

如何使用vue2将DOM元素移动到特定节点位置?

背景:在编写商城页面时,PC端的布局图是按照宽度1920设计的,内部内容区域(main)宽度为1191px,写死的指定宽度。

如何使用vue2将DOM元素移动到特定节点位置?

新页面:随后出现了一个页面,类似于12306的页面,图片部分直接占满了屏幕。

背景:在写商城页面时,PC端给的设计图纸是按照宽度1920给的,内部内容区域(main)1191px,写死的指定宽度。然后新出了一个页面,类似于12306的这个页面,图片部分,直接占满了屏幕的100vw,内部div的宽度,超出了外部的,因此想到了vue3新出的teleport,vue2如何实现这个功能


新建一个teleport组件

点击查看代码

<script> export default { name: 'teleport', props: { /* 移动至哪个标签内,最好使用id */ to: { type: String, required: true } }, mounted() { document.querySelector(this.to).appendChild(this.$el) }, destroyed() { document.querySelector(this.to).removeChild(this.$el) }, render() { return <div>{this.$scopedSlots.default()}</div> } } </script>

从使用页面引入组件
点击查看代码

<template> <div class="logisticsInfo"> <div class="title-box"> <teleport to="#header__center"> <img src="../assets/logisticsInfoImgs/bg-title.png" alt="" class="bg-box"></teleport> </div> </div> </template> <script> import teleport from './components/teleport.vue' export default { name: 'QsMallWebLogisticsInfo', components: { teleport, }, data() { return {} }, mounted() {}, methods: {}, } </script> <style lang="scss" scoped> .logisticsInfo { .title-box { } } </style> <style lang="scss"> #header__center { .bg-box { height: 458px; width: 100%; } } </style>

注意样式不要写在使用属性里 指定转移的节点,通过id的方式,进行绑定
点击查看代码

<div id="header__center"></div> <div class="main"> <router-view ref="mallPage"></router-view> </div>