4

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 2

1

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>

Sign up to request clarification or add additional context in comments.

2 Comments

Yes that's what I need, but I expect the transition to be on the click of the button, I don't know if Vue can handle pesudo properties.
That's why I mentioned you need to adapt it to your situation (instead of .box:hover you'd use .headnew, for example). Your issue has nothing to do with Vue; the Vue code you have so far is fine. It's all about the CSS.
1

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/[email protected]/dist/vue.js"></script>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.