[Vuejs]-How to avoid repeating of code in vuetify?

0👍

You can try like this:

<template>
           <v-btn
              v-for="color in colorsList"
              :key="color.text"
              :color="color.text"
              @click="changeTheme(color.value)"
              class="ma-2"
              style="width:150px;"
            >{{color.text}}</v-btn>
</template>

<script>
export default 
{
  data() 
  {
    return {
      dialog: false,
      theme: "",
      colors: 
      {
        blue: "#2196F3",
        purple: "#9C27B0",
        grey: "#9E9E9E",
        pink: "#E91E63",
        orange: "#FF9800",
        teal: "#009688",
        cyan: "#00BCD4",
        amber: "#FFC107",
        "deep-purple": "#673AB7",
        "deep-orange": "#FF5722",
        green: "#4CAF50"
      }
    };
  },
  computed:
  {
    colorsList()
    {
      return Object.entities.map(entitiy => ({
        text: entity[0],
        value: entity[1]
      }));
    }
  }

0👍

Why not modify the theme? https://vuetifyjs.com/en/customization/theme/

Simply provide a configuration object when initializing vuetify in your app.

// main.js or a separate file where you init vuetify

import Vuetify from 'vuetify';

const opts = {
  theme: {
    themes: {
      light: { /* your list of colors */},
      dark: { /* another list of colors maybe */},
    },
  },
};

export default new Vuetify(opts);

If you need a new array from all color names defined there, you can use Object.keys(this.$vuetify.theme.themes.light).map(). If you’re also using dark theme, you’ll have to modify the code slightly to call from this.$vuetify.theme.themes.dark when this.$vuetify.theme.dark is true.

computed: {
  themeColors() {
    const activeTheme = this.$vuetify.theme.dark ? 'dark' : 'light';
    return Object.keys(this.$vuetify.theme.themes[activeTheme]).map();
  }
}

If you need to set new colors for light/dark, you can simply override the current theme with a new colors object based on the clicked item. This also gives you more control over which colors you want to override, you could only override Primary, but also Secondary, Accent, or any other semantic color name that vuetify uses for the styling of its components.

Leave a comment