debbygigigi / notes

My notes for any technologies of Web, Tech, etc.
9 stars 1 forks source link

vue directive 使用 #36

Open debbygigigi opened 5 years ago

debbygigigi commented 5 years ago

directive (n.) 指令

vue directive 就是使用 v- 作為前綴的指令,主要用來操作 DOM 目前最常用到的就是官方提供的 directive: v-ifv-for 等等 而官方也有提供 custom directive 讓我們撰寫客製的 directive

Name of Directive

一個基本的 directive 至少會有 name,可以沒有 arguments 或 modifiers,像是官方提供的 v-else

<app-navigation v-sticky></app-navigation>

Passing Values to Directive

你可以傳值給 directive

<div v-if="isVisible">Show this</div>

Arguments

<app-navigation v-sticky:bottom></app-navigation>

the name of directive is sticky

一個 directive 只能有一個 Arguments

Modifiers

修飾符,主要會利用 . 串連在 name 後方,能讓 directive 再多一點不一樣的變化

<span v-format.underline>guide</span>

修飾符可以多個:

<span v-format.bold.highlight.underline>guide</span>

上例,modifiers 的值會是 boldhighlightunderline 三個都有


example: v-scroll

來寫一個 scroll 的 directive!

<div v-scroll="handleScroll"></div>

這個 v-scroll 主要的功用是偵測該 element 有 scroll 的行為就觸發 handleScroll 事件(不一定要 handleScroll 總之會連動到我們給他的事件就好)

一個非常簡單的 directive

Vue.directive("scroll", function(el, binding, vnode) {
 if (binding.value) {
     window.removeEventListener("scroll", binding.value);
 }
 window.addEventListener("scroll", binding.value);
});

這裡的 binding.value 就是我們給他的事件 handleScroll,所以我們讓這個 directive 初始化時會觸發 window.addEventListener("scroll", binding.value); 的事件,在綁定前先移除之前綁定的 EventListener

resources