VueJs - Change div color with transition

Viewed 4012

I have a header bar and a button. I can change the color on click but I want the color change with a smooth transition or effect on click. Is it possible to do it with Vue.js?

HTML code

<html>    
    <head>
      <title>My App</title>
    </head>
    <body>
        <div id="app">
            <div class="head" :class="{ headnew : change }"></div>
            <button @click="changeIt">Change me!</button>
        </div>
    </body>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"> 
    </script>
</html>

CSS code

.head {
    background: linear-gradient(-90deg, #84CF6A, #16C0B0);
    height: 60px;
    margin-bottom: 15px;
  }

.headnew {
    background: red;
    height: 60px;
    margin-bottom: 15px;
}

JS code

var app = new Vue({
    el: "#app",
    data: {
        change : false
    },
    methods: {
        changeIt() {
            this.change = true
        }
    }
})
2 Answers

Background gradients cannot be animated, but you can hack it by fading in another element (the ::before pseudo element in this case) that overlaps the background.

Here's a generic HTML+CSS example which you can easily adapt to your code:

.box {
  width: 100px;
  height: 100px;
  background: linear-gradient(to top, blue, yellow);
  position: relative;
  z-index: 0;
}

.box::before {
  content: '';
  position: absolute;
  z-index: -1;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  background-color: red;
  opacity: 0;
  transition: opacity 0.2s linear;
}

.box:hover::before {
  opacity: 1;
}
<div class="box">Some text</div>

You could do it simply by adding transition property to your .head as follow :

  .head {
  ...
    transition: background 6s ease;
   }

check the following working solution :

var app = new Vue({
  el: "#app",
  data: {
      change : false
  },
  methods: {
      changeIt() {
          this.change = true
      }
  }
})
.head {
    background: linear-gradient(-90deg, #84CF6A, #16C0B0);
    height: 60px;
    margin-bottom: 15px;
    transition: background 6s ease;
  }


.headnew {
    background: red;
    height: 60px;
    margin-bottom: 15px;
}
  <div id="app">
    <div class="head" :class="{ headnew : change }"></div>
    <button @click="changeIt">Change me!</button>
</div>
  <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>

Related