Vue里如何注冊全域自定義指令?
根據Vue官網給出的注冊自定義聚焦示例,撰寫以下自定義拖拽指令…
一、首先創建一個index.js檔案,用于撰寫我們注冊自定義指令的代碼
export default (vue) => {
/* 1、自定義全域自動聚焦 這個是官網給出的
vue.directive('focus', {
inserted: function (el) {
el.focus()
}
}) */
/*2自定義全域拖拽指令 */
vue.directive('drag', {
inserted: function (el, binding, vnode) { //inserted是一個鉤子函式,表示被系結的元素插入到 DOM
let modalBox = el
//獲取視口寬度及高度(視口高度與寬度指的就是你能看得見的瀏覽器視窗的高度與寬度)
let watchWidth = modalBox.offsetParent.offsetWidth //前提要給body和html寬高設為100%
let watchHeight = modalBox.offsetParent.offsetHeight
//獲取被系結元素自身寬度及高度
let modalWidth = window.getComputedStyle(modalBox).width
modalWidth = parseInt(modalWidth.substring(0,modalWidth.length - 2))
let modalHeight = window.getComputedStyle(modalBox).height
modalHeight = parseInt(modalHeight.substring(0,modalHeight.length - 2))
//滑鼠按下即開始監聽
modalBox.onmousedown = e1 => {
modalBox.style.cursor = "pointer"; //這個是滑鼠劃過手型效果,不喜歡的可以不加
modalBox.style.zIndex = "999"; //拖動時優先級,很好理解
//算出滑鼠相對元素的的位置
let width = e1.clientX - modalBox.offsetLeft
let height = e1.clientY - modalBox.offsetTop
document.onmousemove = e2 => {
//滑鼠的位置減去滑鼠相對元素的位置得到元素自身的位置
let modalLeft = e2.clientX - width
let modalTop = e2.clientY - height
//下面的4個if判斷是用來限制拖動時盒子不要自動超出瀏覽器現有寬度與高度,
//不理解你就把4個if全刪掉,再去拖拽,大范圍的拖拽,看看會發生什么你就懂了
if(modalLeft < 0){
modalLeft = 0
}
if(modalTop < 0){
modalTop = 0
}
if(modalLeft + modalWidth >= watchWidth){
modalLeft = watchWidth - modalWidth
}
if(modalTop + modalHeight >= watchHeight){
modalTop = watchHeight - modalHeight
}
//開始移動
modalBox.style.position = 'absolute';
modalBox.style.left = modalLeft + 'px'
modalBox.style.top = modalTop + 'px'
}
}
//完成拖拽時記得把監聽的事件移除
document.onmouseup = () =>{
document.onmousemove = null
modalBox.style.cursor = "";
}
},
//update也是個鉤子函式,在這個鉤子函式里繼續完成取消事件監聽
//這里提醒:不要把onmousedown事件也取消了,如果取消了就只能拖拽一次了!!仔細點喲!
update: (el, binding, vnode) => {
document.onmouseup = null
}
})
}
二、來到我們的main.js檔案,把我們寫好的自定義指令呼叫起來,即注冊!
//注冊自定義指令
import Vue from 'vue'
import Directive from './directive/index.js' //因為我把自定義指令封裝成一個函式了,
//只要呼叫它,傳入Vue就行啦!
Directive(Vue)
Vue.config.productionTip = false
new Vue({
render: h => h(App),
}).$mount('#app')
三、以上兩步即完成了自定義指令的注冊,下面我們到任意一個組件使用它即可
<template>
<div id="app">
<div v-drag class="box1">{{data}}</div>
</div>
</template>
<script>
export default {
name: 'App',
data(){
return {
data: '你好啊vue自定義指令'
}
}
}
</script>
<style>
.box1{
height: 300px;
width: 300px;
background-color: paleturquoise;
}
</style>
最后:這里我就不給大家看效果了,大家自己去看效果,只需要在需要拖拽的盒子上面加個 v-drag指令就行了,非常方便;本示例并不復雜,無非就是操作DOM,修改位置,希望能給大家帶來經驗,然后自己去注冊一些更加實用、更加牛 * 的自定義指令!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/132174.html
標籤:其他
上一篇:JavaScript調戲了上帝
下一篇:CTF Forms
