一尘子、道法自然、博客园、前端

vue2 如何实现将dom元素转移到指定节点

背景:在写商城页面时,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>
posted @ 2022-05-12 13:59  一尘子!  阅读(555)  评论(0编辑  收藏  举报
Live2D
返回顶端