/ Gists / VUE - Directives
On gists

VUE - Directives

Vue.js

Directives.vue Raw #

export default {
  install (Vue) {

    Vue.directive('test-demo', {
      mounted(el, binding) {
        
        const modifiers = binding.modifiers
        const state = binding.arg === "a" ? "a" : "b"

        if (state === 'a') {
          el.style.color = 'red'
        } else {
          el.style.color = 'green'
        }

        if (modifiers.underline) {
          el.style.textDecoration = "underline"
        }
        if (modifiers.overline) {
          el.style.textDecoration = "overline"
        }

      }
    })

    Vue.directive('width', {
      mounted: function (el, binding) {
        el.style.width = binding.value + 'px'
      }
    })

    // mounted + update both
    Vue.directive('color-swatch', function (el, binding) {
      el.style.backgroundColor = binding.value
    })

    Vue.directive('demo', function (el, binding) {

      el.style.color = binding.value.color // => "white"
      el.textContent = binding.value.text
    })
  }

}

index.html Raw #

<h1 v-test-demo:A>TEST DIREKTIVY A</h1>
<h1 v-test-demo:B>TEST DIREKTIVY B</h1>
<h1 v-test-demo>TEST DIREKTIVY empty</h1>
<h1 v-test-demo.underline>TEST DIREKTIVY underline</h1>
<h1 v-test-demo.overline>TEST DIREKTIVY overline</h1>
<h1 v-width="100" style="border: 1px solid red">:-)</h1>
<h1 v-width="300" style="border: 1px solid red">:-)</h1>
<div v-demo="{ color: 'red', text: 'hello!' }">cus</div>

assign-function.js Raw #

Vue.directive('scroll', {
  inserted: function(el, binding) {
    let f = function(evt) {
      if (binding.value(evt, el)) {
        window.removeEventListener('scroll', f);
      }
    };
    window.addEventListener('scroll', f);
  },
});

// main app
new Vue({
  el: '#app',
  methods: {
   handleScroll: function(evt, el) {
    if (window.scrollY > 50) {
      TweenMax.to(el, 1.5, {
        y: -10,
        opacity: 1,
        ease: Sine.easeOut
      })
    }
    return window.scrollY > 100;
    }
  }
});



<div class="box" v-scroll="handleScroll">
  <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A atque amet harum aut ab veritatis earum porro praesentium ut corporis. Quasi provident dolorem officia iure fugiat, eius mollitia sequi quisquam.</p>
</div>