在vue中封装一个类似电商的从右至左滚动公告的组件

使用vue-cli封装一个轮播文字通告组件:

我们在使用电商网站经常会看到轮播文字的通告;这是一个从右至左的滚动的文字播放

在这里插入图片描述

这是封装好了demo组件

<template>
  <div class="wrap">
    <div id="box">
      <div id="marquee">{{text}}</div>
      <div id="copy"></div>
    </div>
    <div id="node">{{text}}</div>
  </div>
</template>
<script>
export default {
  props: ['lists'], // 父组件传入数据, 数组形式 [ "连雨不知春去","一晴方觉夏深"]
  data () {
    return {
      text: '' // 数组文字转化后的字符串
    }
  },
  methods: {
    move () {
      // 获取文字text 的计算后宽度  (由于overflow的存在,直接获取不到,需要独立的node计算)
      let width = document.getElementById('node').getBoundingClientRect().width
      let box = document.getElementById('box')
      let copy = document.getElementById('copy')
      copy.innerText = this.text // 文字副本填充
      let distance = 0 // 位移距离
      // 设置位移
      setInterval(function () {
        distance = distance - 1
        // 如果位移超过文字宽度,则回到起点
        if (-distance >= width) {
          distance = 16
        }
        box.style.transform = 'translateX(' + distance + 'px)'
      }, 40)
    }
  },
  // 把父组件传入的arr转化成字符串
  mounted: function () {
    for (let i = 0; i < this.lists.length; i++) {
      this.text += ' ' + this.lists[i]
    }
  },
  // 更新的时候运动
  updated: function () {
    this.move()
  }
}
</script>
<style scoped>
  /*样式的话可以写*/
  .wrap {
    overflow: hidden;
    background: white;
  }
     #box {
       width: 500%;
     }
     #box div {
       float: left;
     }
     #marquee {
       margin: 0 16px 0 0;
     }
     #node {
       position: absolute;
       z-index: -99;
       top: -99px;
     }
</style>

在需要轮播文字的组件中调用

<template>
    <div>
      <demo :lists="lists"></demo>
    </div>
</template>

<script>
import demo from './demo'
export default {
  components: {
    demo
  },
  data () {
    return{
      lists:['温馨提示:根据相关规定,请旅客凭有效身份证上车,无需抵押其他']   //轮播中的文字
    }
  }
}
</script>

<style scoped>

</style>

以上就是这篇文章的全部内容

猜你喜欢

转载自blog.csdn.net/weixin_41997724/article/details/82782100