<template>
  <div class="rollcon" :ref="'r_'+myref">
    <span :class="{shenglv:(parentW < childW && !active)}" :ref="myref" :style="`transform: translateX(${translate}px);
    ${`width: ${(parentW < childW && !active)?`calc(100% - ${mgin||10}px)`:'auto'}`}`">{{name}}</span>
  </div>
</template>
<script>
export default {
  props:['name','myref','active','offset','mgin'],

  data(){
    return {
      translate: 0,
      parentW:0,
      childW:0,
      inter:null
    }
  },
  watch:{
    active:{
      immediate:true,
      handler:function (newVal) {
        if (newVal) {
          this.init()
        }
      }
    }
  },
  methods:{
    clearInter(){
      clearInterval(this.inter)
      this.inter = null
    },
    init(){
      this.$nextTick(() => {
          this.parentW = this.$refs['r_'+this.myref] ? this.$refs['r_'+this.myref].offsetWidth : 0
          this.childW = this.$refs[this.myref] ? this.$refs[this.myref].offsetWidth : 0
          this.start()
      })
    },
    start(){
      let fn = ()=>{
        this.translate -= 0.2
        if ((this.parentW - this.translate -  (this.mgin || 0))>(this.childW + this.parentW)) {
          this.translate = this.parentW
        }
        if (!this.active) {
          this.translate = 0
          this.clearInter()
          return
        }
        // requestAnimationFrame(fn)
      }

// console.log('==============');
//       console.log(this.parentW, this.childW);
      
      if (this.parentW < this.childW) {
        this.clearInter()
        this.inter = setInterval(() => {
            fn()
        }, 10);
      }
    }
  },
  mounted(){
    this.init()
  },
  beforeDestroy(){
  }
}
</script>

<style lang="less" scoped>
.rollcon{
  width: 100%;
  display: inline-block;
  >span{
    width: auto;
    display: inline-block;
    // transition: 0.3s transform ease;
    vertical-align:unset;
  }
  .shenglv{
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
    line-height: 100%;
    vertical-align: baseline;
  }
}
</style>