DRY your code with Vue.js

in #development5 years ago

Screenshot 2019-01-02 at 6.21.06 PM.png

DRY also stands for Don't Repeat Yourself, which is a popular phrase for Ruby on Rails developer, which means that you should not repeat your code more than once.

In Vue.js, with the power of Mixins and Directive, these can be achieved easily.

Mixins

Mixins are just like sass mixins, it can save you from writing bunch of codes.

const clickMixin = Vue.mixin({
  methods: {
    triggerClick: function() {
      this.data = `Hello ${Math.random()}!`
    }
  }
})

Something like this can be shared across multiple components by simply use it by using mixins and pass it as an array.

mixins: [clickMixin]

Do becareful about the lifecycle of mixins when being used, mixins' lifecycle will run before the component's lifecycle kicks in.

Directives

Directive is use for DOM element.

Vue.directive("green", function(el) {
  el.style.color = "green";
});

by using it in html, you simply add in v-green into your div, and you can get a green color text.

<h1 v-green v-on:click="triggerClick">{{data}}</h1>

Checkout sample at Codepen

https://codepen.io/superoo7/pen/ReMxRX

Sort:  

You’ve been upvoted by TeamMalaysia community. Do checkout other posts made by other TeamMalaysia authors at http://steemit.com/created/teammalaysia

To support the growth of TeamMalaysia Follow our upvotes by using steemauto.com and follow trail of @myach

Vote TeamMalaysia witness bitrocker2020 using this link vote for witness

帅哥/美女!欢迎在steemauto里设置跟赞 @cnbuddy 给整个cn区点赞倘若你想让我隐形,请回复“取消”。

Hi, @superoo7!

You just got a 1.3% upvote from SteemPlus!
To get higher upvotes, earn more SteemPlus Points (SPP). On your Steemit wallet, check your SPP balance and click on "How to earn SPP?" to find out all the ways to earn.
If you're not using SteemPlus yet, please check our last posts in here to see the many ways in which SteemPlus can improve your Steem experience on Steemit and Busy.

Coin Marketplace

STEEM 0.27
TRX 0.11
JST 0.032
BTC 64579.45
ETH 3101.05
USDT 1.00
SBD 3.83