M
M
Mike2019-04-30 21:11:07
Vue.js
Mike, 2019-04-30 21:11:07

How to change the color of divs?

There are 10 div blocks . There are two buttons redColor and greenColor . After clicking on one of the buttons, the first block of the div should change its color to the corresponding button, then the second block, the third and so on.
Now if you click on redColor everything works fine, but if you click on greenColor after that, the colors of the previous blocks change to green. I need them to keep their colors.
Here is what I have, I can't figure out how to change my code further.

<template>
    <div>
        This is Profile.vue
        <li v-for="(x, i) of 10" :key="i">
            <ul :class="i<=index?mycolor:'black'">
                {{ x }}
            </ul>
        </li>
      <button @click="redColor()">red</button>
      <button @click="greenColor()">green</button>
    </div>
</template>

import { mapGetters } from 'vuex'
export default {
    name: 'Profile',
    data() {
        return {
            index: -1,
            mycolor: '',
        }
    },
    computed: mapGetters({
        profile: 'profile',
    }),
    methods: {
        greenColor: function() {
            this.index++
            console.log(this.index);
            this.mycolor = 'green'
            if (this.index === 10) {
                this.index = -1;
            }
        },
        redColor: function() {
            this.index++;
            this.mycolor = 'red'
            console.log(this.index);
            if (this.index === 10) {
                this.index = -1;
                }
            }
        }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-04-30
@google_online

Obviously, it is difficult to set the color of several blocks using one string variable.
Let there be an array whose elements set the color of individual blocks:

data: () => ({
  items: Array(10).fill(null),
  ...

<ul>
  <li v-for="(n, i) in items" :style="index < i || { color: n }">
    {{ i }}
  </li>
</ul>

Copy-pasting buttons and methods for switching colors is not very cool - what if there are not two colors, but five? Ten? Fourty? Make forty different methods and manually write the markup for forty buttons?
Leave the method alone, and set the color as a parameter:
methods: {
  next(color) {
    const { index, items } = this;
    this.index = index === items.length - 1 ? 0 : index + 1;
    items.splice(this.index, 1, color);
  },
  ...

And add the colors available for assignment into an array, on the basis of which buttons are created:
data: () => ({
  colors: [ 'red', 'lime', 'blue', 'orange', 'magenta', 'aqua', 'yellow' ],
  ...

<button v-for="c in colors" @click="next(c)">{{ c }}</button>

https://jsfiddle.net/wcjkft23/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question