Vue自定義指令的概念及使用。
阿新 • • 發佈:2021-01-14
技術標籤:vue
Vue自定義指令:directive
在Vue中,除了預設設定的核心指令(v-model
和v-show
),Vue也允許自定義指令directive
.
自定義指令分為全域性自定義指令
和區域性自定義指令
。
全域性自定義指令:
使用Vue.directive
來全域性註冊指令。
Vue.directive('focus', {
// 當繫結元素插入到 DOM 中。
inserted: function (el) {
// 聚焦元素
el.focus()
}
})
區域性自定義指令:
在元件或者Vue建構函式中接收一個directives
的選項,來註冊區域性指令。
directives: {
// 註冊一個區域性的自定義指令 v-focus
focus: {
// 指令的定義
inserted: function (el) {
// 聚焦元素
el.focus()
}
}
}
自定義指令的鉤子函式:
指令定義函式提供了幾個鉤子函式:
bind
:繫結元素
的時候呼叫inserted
:繫結的元素插入父節點
時呼叫Updata
:繫結元素的值改變之前
呼叫componentupdata
:繫結的元素改變之後
呼叫unbind
:解綁元素
的時候呼叫
鉤子函式函式:
el
:繫結的元素,用來操作DOMbinding
:繫結的物件資訊,包含以下屬性。name
: 指令的名字value
: 指令的值oldValue
: 指令繫結的前一個值,僅在update
和componentUpdated
鉤子中可用。無論值是否改變都可用。expression
: 繫結值的字串形式。 例如 v-my-directive=“1 + 1” , expression 的值是 “1 + 1”。arg
: 傳給指令的引數。例如 v-my-directive:foo, arg 的值是 “foo”。modifiers
: 一個包含修飾符的物件。 例如: v-my-directive.foo.bar, 修飾符物件 modifiers 的值是 { foo: true, bar: true }。
vnode
: Vue 編譯生成的虛擬節點,查閱 VNode API 瞭解更多詳情。oldVnode
: 上一個虛擬節點,僅在 update 和 componentUpdated 鉤子中可用。
使用Vue自定義指令封裝一個拖拽的盒子
Vue.directive("drag", { //指令的名稱
inserted: function (el, binding) { //當被繫結的元素插入到 DOM 中時
el.style.position = "absolute";
el.style.left = binding.arg.left + "px";
el.style.top = binding.arg.top + "px";
el.onmousedown = function (e) {
var x = e.offsetX;
var y = e.offsetY;
document.onmousemove = function (eve) {
el.style.left = eve.clientX - x + "px";
el.style.top = eve.clientY - y + "px";
}
document.onmouseup = function () {
document.onmousemove = null;
document.onmouseup = null;
}
}
}