vue.js實(shí)現(xiàn)可拖拽菜單的方法:【import "@/assets/second.css";export default {name: "HelloWorld",directives: {move(el, bindings) {...】。

在給出正式的實(shí)現(xiàn)代碼之前,我們要先來了解一點(diǎn)相關(guān)知識(shí)點(diǎn)。
知識(shí)點(diǎn)一:
vue中的自定義指令 directive
// 注冊(cè)一個(gè)全局自定義指令 `v-focus`
Vue.directive('focus', {
// 當(dāng)被綁定的元素插入到 DOM 中時(shí)……
inserted: function (el) {
// 聚焦元素
el.focus()
}
})
// 注冊(cè)局部自定義指令
directives: {
focus: {
// 指令的定義
inserted: function (el) {
el.focus()
}
}
}
// 在此我們用的是局部知識(shí)點(diǎn)二:js
onmousedown :鼠標(biāo)按下事件 clientX :時(shí)鼠標(biāo)指針相對(duì)于瀏覽器頁面(或客戶區(qū))的水平坐標(biāo) document.getElementById :通過id獲取節(jié)點(diǎn) offsetWidth :獲取的是盒子最終的寬 onmousemove :鼠標(biāo)移動(dòng)事件 onmouseup :鼠標(biāo)釋放事件
效果圖:


頁面代碼:
<template>
<el-container>
<el-main>
<div class="myBox">
<div id="silderLeft">
<div class="menuList">側(cè)欄菜單區(qū)</div>
<div class="moveBtn" v-move></div>
</div>
<div class="silderRight">右邊自適應(yīng)大小,黃色的為拖拽的按鈕</div>
</div>
</el-main>
</el-container>
</template>
<script>
import "@/assets/second.css";
export default {
name: "HelloWorld",
directives: {
move(el, bindings) {
el.onmousedown = function(e) {
var init = e.clientX;
var parent = document.getElementById("silderLeft");
var initWidth = parent.offsetWidth;
document.onmousemove = function(e) {
var end = e.clientX;
var newWidth = end - init + initWidth;
parent.style.width = newWidth + "px";
};
document.onmouseup = function() {
document.onmousemove = document.onmouseup = null;
};
};
}
},
data() {
return {
msg: "我是第二頁"
};
},
methods: {},
mounted() {},
created() {},
updated() {}
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>樣式代碼:
.myBox{
width: 100%;;
height: 700px;
border: 1px solid red;
display: flex;
}
#silderLeft{
width: 250px;
height: 100%;
background-color: #999;
position: relative;
/* overflow-y: auto; */
}
/* 拖動(dòng)條 */
.moveBtn{
height: 100%;
width: 10px;
/* opacity: 0; */
position: absolute;
right: 0px;
top: 0;
cursor: col-resize;
background-color: yellow;
}
.menuList{
background-color: yellowgreen;
/* height: 120%; */
}
.silderRight{
height: 100%;
background-color: sandybrown;
flex: 1;
}可以修改自定義命令,設(shè)置一個(gè)最小拖拽寬度
directives: {
move(el, bindings) {
el.onmousedown = function(e) {
var init = e.clientX;
console.log('init',init);
var parent = document.getElementById("sidebar");
var initWidth = parent.offsetWidth;
document.onmousemove = function(e) {
var end = e.clientX;
// end - init表示鼠標(biāo)移動(dòng)的距離
// end為鼠標(biāo)移動(dòng)的寬度,可用于設(shè)置最小寬度
if(end > 250){
var newWidth = end - init + initWidth;
parent.style.width = newWidth + "px";
}else{
end = 250;
// 最小寬度242
parent.style.width = 242 + "px";
}
};
document.onmouseup = function() {
document.onmousemove = document.onmouseup = null;
};
};
}
}





