v-stylish

Vue.js directives to easly manipulate dynamic classes and styles

Why v-stylish?

Some times I just don't want to create an object to set a dynamic class or style to an element. So I brought this feature from Angular

Instalation

npm install --save v-stylish

Installing as Plugin

import Vue from 'vue';
import vStylish from 'v-stylish';

Vue.use(vStylish);

Installing manually

import Vue from 'vue';
import { vClass, vStyle } from 'v-stylish';
  
Vue.directive(vClass.name, vClass);
Vue.directive(vStyle.name, vStyle);

How to use it

v-class

To toggle a single class into an element you just need to use the directive:
v-class:your-class="Boolean".

The class will be set as written in the directive.

Example


is-blue class is inactive

Source


<template>
  <div>
    <button type="button" @click="isBlue = !isBlue">toggle</button>

    <p v-class:is-blue="isBlue">
      is-blue class is {{ isBlue ? 'active' : 'inactive' }}
    </p>
  </div>
</template>

<script>
  export default {
    name: 'vClassDemo',
    data() {
      return {
        isBlue: false
      };
    }
  };
</script>

<style scoped>
  .is-blue {
    background-color: darkblue;
    color: lightblue;
  }
</style>

v-style

To set a single style attribute into an element you just need to use the directive:
v-style:attribute.suffix="Number | String".

You may write the style attribute as CammelCase or kebab-case: fontWeight or font-weight.

If necessary you may set a suffix to the value as a directive modifier, example:
v-style:padding.px="14" will set the value 14px to the element padding
v-style:padding.%="14" will set the value 14% to the element padding

Example


font-weight: 400


Padding 0px

Padding 0%

Source


<template>
  <div>
    <label>Font-weight:</label><input v-model="fontWeight" />
    <p v-style:fontWeight="fontWeight">
      font-weight: {{ fontWeight }}
    </p>
    <hr />
    <label>Padding:</label><input v-model="padding" />
    <div
      class="square"
      v-style:padding.px="padding">
      Padding {{ padding }}px
    </div>
    <br />
    <div
      class="square"
      v-style:padding.%="padding">
      Padding {{ padding }}%
    </div>
  </div>
</template>

<script>
  export default {
    name: 'vStyleDemo',
    data() {
      return {
        padding: 0,
        fontWeight: 400
      };
    }
  };
</script>

<style scoped>
  .square {
    border: 1px solid black;
  }
</style>