0

New to vue.js and am wondering if this is a possible outcome. I have 8 different options of a background color that I want to render based on the given class name. I can achieve this with css but was wondering if there is a dynamic way with vue to accomplish this. my ideal outcome would be just change the class name in the markup and it will then render that associated bg color.

HTML:

<div class="page-header__container" :style="{ background: color }">
    <div class="container">
      <div class="row">
        <div class="page-header">
          <h1 class="page-header__text">
            Page Header Lorem ipsUm
          </h1>
</div>

js:

export default {
   name: 'Header',
   data() {
   return {
   color: '#333'
    };
   }
 };

css:

bg-one{
background-color: #673AB7
}
bg-two{
background-color: #7293A0
}
bg-three{
background-color: #45B69C
}
1
  • 1
    if u want to apply any css class declarated just have to bind the class and not style, i mean :class="color" Commented Jan 13, 2020 at 18:28

1 Answer 1

1

https://jsfiddle.net/kyz19b7r/

new Vue({
  el: "#app",
  data: {
  	bgColour: 'blue',
    classes: [ 'blue', 'red', 'green'
    ]
  }
})
body {
  background: #fff;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

.blue {
  background: blue;
}

.red {
  background: red;
}

.green {
  background: green;
}
<div id="app" :class="bgColour">
  <select v-model="bgColour">
    <option v-for="myClass in classes" :value="myClass">{{ myClass }}</option>
  </select>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.