Javascript/Vue.js

[Vue] Directive hook

Icarus8050 2019. 9. 13. 14:23
반응형

bind(el, binding, vnode)

  • Directive 가 엘리먼트에 처음 바인딩 될 때 한 번만 호출됩니다.

inserted(el, binding, vnode)

  • 바인딩된 엘리먼트가 부모 노드에 삽되었을 때 호출됩니다.

update(el, binding, vnode, oldVnode)

  • 컴포넌트가 업데이트되고난 후에 호출됩니다. 자식 컴포넌트는 아직 업데이트 되기 전에 호출됩니다.
  • 새로운 가상돔과 이전의 가상돔을 파라미터로 받습니다.

componentUpdated(el, binding, vnode, oldVnode)

  • 컴포넌트가 업데이트되고난 후에 호출되지만 update hook과 다르게 자식 컴포넌트까지 업데이트된 후에 호출됩니다.

unbind(el, binding, vnode)

  • 디렉티브가 엘리먼트로부터 언바인딩되었을 경우에 한 번만 호출됩니다.

 


Custom Directive

 사용자 지정 디렉티브는 아래와 같은 예시로 사용할 수 있습니다.

 

main.js

import Vue from 'vue'
import App from './App.vue'

Vue.directive('highlight', {
  bind(el, binding, vnode) {
    el.style.backgroundColor = 'red';
  }
});

new Vue({
  el: '#app',
  render: h => h(App)
});

 main.js에서 Vue.directive() 를 통해 첫 번째 인자로 사용자 지정 디렉티브의 이름을 지정합니다. 두 번째 인자로는 디렉티브 훅을 담고 있는 객체를 인자로 넣습니다. 위의 예시에서는 'highligh' 라는 이름의 디렉티브를 정의하였고, 바인딩하면 해당 엘리먼트의 배경색을 붉은 색으로 변경하도록 하였습니다.

 

 

App.vue

<template>
    <div class="container">
        <div class="row">
            <div class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3">
                <h1>Built-in Directives</h1>
                <p v-text="'Some Text'"></p>
                <p v-html="'<strong>strong text</strong>'"></p>
            </div>
        </div>
        <hr>
        <div class="row">
            <div class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3">
                <h1>Custom Directives</h1>
                <p v-highlight>Color this</p>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
    }
</script>

<style>
</style>

 main.js 에서 디렉티브를 정의하고 두 번째 row 클래스를 가진 div 영역에서 p 태그에 v-highlight 디렉티브를 바인딩 시켰습니다. 그 결과 p 태그 영역의 배경색이 빨간색으로 변경된 것을 볼 수 있습니다.


 이번엔 다른 방법으로 아래와 같이 디렉티브를 바인딩시킬 수도 있습니다.

import Vue from 'vue'
import App from './App.vue'

Vue.directive('highlight', {
  bind(el, binding, vnode) {
    //el.style.backgroundColor = 'red';
    el.style.backgroundColor = binding.value
  }
});

new Vue({
  el: '#app',
  render: h => h(App)
});
<template>
    <div class="container">
        <div class="row">
            <div class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3">
                <h1>Built-in Directives</h1>
                <p v-text="'Some Text'"></p>
                <p v-html="'<strong>strong text</strong>'"></p>
            </div>
        </div>
        <hr>
        <div class="row">
            <div class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3">
                <h1>Custom Directives</h1>
                <p v-highlight="'red'">Color this</p>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
    }
</script>

<style>
</style>

 디렉티브를 바인딩하는 태그에서 값을 넣어주면 main.js 에서와 같이 binding.value 에 해당 값이 전달됩니다.

 

 

<p v-highlight:background="'red'">Color this</p>

 위와 같이 background 로 파라미터를 지정해주면 아래와 같이 binding.arg 에 값을 전달받을 수도 있습니다.

Vue.directive('highlight', {
  bind(el, binding, vnode) {
    //el.style.backgroundColor = 'red';
    //el.style.backgroundColor = binding.value
    if (binding.arg == 'background') {
      el.style.backgroundColor = binding.value;
    } else {
      el.style.color = binding.value;
    }
  }
});

 

Local Directive

export default {
        directives: {
            'local-highlight': {
                bind(el, binding, vnode) {
                    //el.style.backgroundColor = 'red';
                    //el.style.backgroundColor = binding.value;
                    let delay = 0;
                    if (binding.modifiers['delayed']) {
                        delay = 3000;
                    }
                    setTimeout(() => {
                        if (binding.arg == 'background') {
                            el.style.backgroundColor = binding.value;
                        } else {
                            el.style.color = binding.value;
                        }
                    }, delay);
                }
            }
        }
    }

 로컬 디렉티브는 위와 같이 정의할 수 있습니다. 돔에 바인딩 시킬 때는 아까와 같은 방법으로 가능합니다.

<p v-local-highlight:background.delayed="'red'">Color this</p>

 


참고자료

https://kr.vuejs.org/v2/guide/custom-directive.html#%ED%95%A8%EC%88%98-%EC%95%BD%EC%96%B4

https://www.udemy.com/vuejs-2-the-complete-guide/

 

반응형