티스토리 뷰

728x90

 

디렉티브라 함은 v-시작하는 대표적으로 v-model, v-show 말합니다. 이 편리한 기능을 커스텀으로 만들어서 사용할 수 있습니다.

 

특정 기능을 directive로 구현할 수도 있고 component로도 구현할 수 있습니다.

2가지 옵션 중에 어떤 것을 선택해야 할지 의문이 들었는데 Vue.js 공식 사이트에서 그 차이점을 알 수 있었습니다.

 

Directives vs Components
Vue has a clearer separation between directives and components. Directives are meant to encapsulate DOM manipulations only, while components are self-contained units that have their own view and data logic. In AngularJS, directives do everything and components are just a specific kind of directive.

 

한글로 번역하면

 

Vue는 디렉티브와 컴포넌트를 명확하게 구분합니다. 지시어는 DOM 조작만 캡슐화 하기 위한 것이고 컴포넌트는 자체 뷰와 데이터 로직이 있는 자체의 포함 단위입니다. Angular에서는 이 둘 사이에 많은 혼란이 있습니다.

 

directive는 Dom 조작만 할 경우

component는 뷰+데이터 로직이 있는 단위

 

그래서 예제를 보면 Dom 조작 코드만 존재합니다.

 

Vue.directive('focus', {
  inserted: function (el) {
    el.focus()
  }
})
<input v-focus>

 

 

훅(Hook) 함수

디렉티브 객체는 여러가지 훅 함수를 제공합니다. 설명은 다음과 같습니다.

  • bind: 디렉티브가 처음 엘리먼트에 바인딩될 때 한번 호출됩니다.
  • inserted: 바인딩된 엘리먼트가 부모 노드에 삽입되었을 때 호출됩니다.
  • update: 포함하는 컴포넌트가 업데이트된 후 호출됩니다. 자식 컴포넌트가 업데이트되기 전에 됩니다. 
  • componentUpdated: 포함하고 있는 컴포넌트와 그 자식들 이 업데이트된 후에 호출됩니다.
  • unbind: 디렉티브가 엘리먼트로부터 언바인딩된 경우 한번 호출됩니다.

훅(Hook) 전달 인자

  • el: 디렉티브가 바인딩된 엘리먼트로 이 전달자로 DOM 조작을 할 수 있습니다.
  • binding: 다음 속성을 가진 객체입니다.
    • name: 디렉티브 이름, v- {mydirective}인 경우  mydirective값이 전달됩니다.
    • value: 디렉티브에서 전달받은 값. 예를 들어 v-mydirective="2"면 2가 전달됩니다.
    • oldValue: 이전 값. update와 componentUpdated에서만 사용할 수 있습니다. 값이 변경되었는지 확인할 때 사용합니다.
    • expression: 표현식 문자열. 예를 들어 v-mydirective="1 + 1"이면, 표현식은 "1 + 1"입니다.
    • arg: 디렉티브의 전달 인자가 있는 경우에만 값이 존재합니다. 예를 들어 v-mydirective:foo 이면 "foo" 입니다.
    • modifiers: 포함된 수식어 객체가 있는 경우에만 존재합니다. 예를 들어 v-mydirective.foo.bar이면, 수식어 객체는 { foo: true, bar: true }입니다.
  • vnode: Vue 컴파일러가 만든 버추얼 노드. VNode API에 전체 설명이 있습니다.
  • oldVnode: 이전의 버추얼 노드. update와 componentUpdated에서만 사용할 수 있습니다.

 

디렉티브의 agument를 아래처럼 처리할 수도 있습니다.

 

<div id="dynamicexample">
  <h3>Scroll down inside this section ↓</h3>
  <p v-pin:[direction]="200">I am pinned onto the page at 200px to the left.</p>
</div>
Vue.directive('pin', {
  bind: function (el, binding, vnode) {
    el.style.position = 'fixed'
    var s = (binding.arg == 'left' ? 'left' : 'top')
    el.style[s] = binding.value + 'px'
  }
})

new Vue({
  el: '#dynamicexample',
  data: function () {
    return {
      direction: 'left'
    }
  }
})

 

디렉티브 값을  object 할당한 경우 binding에서 해당 값을 가져와 쓸 수 있습니다.

 

<div v-demo="{ color: 'white', text: 'hello!' }"></div>
Vue.directive('demo', function (el, binding) {
  console.log(binding.value.color) // => "white"
  console.log(binding.value.text)  // => "hello!"
})

 

프로젝트를 하면서 지금까지는 필요하다고 느낀 적이 없었네요.

나중에 사용하게 되면 업데이트하겠습니다.

728x90
댓글