b3n10
b3n10

Reputation: 55

VueJS - rotate before displaying element

I'm trying to display a line in different directions. Both vertical and horizontal directions work as expected. But for diagonal direction I need to rotate it first before it is displayed. Problem is it displays the line vertically then rotates to 135deg. I understand the element needs to be displayed before it can be rotated. So how can I make this work?

Here is a working demo

HTML:

<div id="app">
  <button @click="toggle">Toggle</button>
  <span>Direction: {{ direction }}</span>
  <transition name="line-transition">
    <div v-if="direction"
       class="line"
      :class="direction">
    </div>
  </transition>
</div>

VueJS

new Vue({
  el: "#app",
  data: {
    direction: null
  },
  methods: {
    toggle: function(){
      const arr = [ 'vertical', 'horizontal', 'diagonal']

      /* random select */
      this.direction = arr[Math.floor(Math.random() * arr.length)]

      /* hide line before toggling direction */
      setTimeout(() => {
            this.direction = null
      }, 1000)
    }
  }
})

CSS:

.line.vertical {
  width: 10px;
  height: 100px;
}
.line.horizontal {
  width: 100px;
  height: 10px;
}
.line.diagonal {
  transform: rotate(135deg);
  width: 10px;
  height: 100px;
}

.line-transition-enter-active,
.line-transition-leave-active {
  animation: slidein 1s;
}

@keyframes slidein {
  from {
    transform: scaleX(0) scaleY(0);
  }
   to {
    transform: scaleX(1) scaleY(1);
  }
}

Upvotes: 1

Views: 694

Answers (1)

Temani Afif
Temani Afif

Reputation: 272842

And idea is to use a pseudo element to create the diagonal line so you avoid the conflit between using tranform on the animated element:

.line.diagonal {
  width:100px;
  height:100px;
  background:transparent;
}
.line.diagonal:before {
  content:"";
  top:0;
  left: calc(50% - 5px);
  position:absolute;
  transform: rotate(135deg);
  border-radius: inherit;
  background: blue;
  width: 10px;
  height: 100px;
}

Full code:

https://jsfiddle.net/m4g198r2/28/

Upvotes: 1

Related Questions