公司产品使用的是vue-element-admin框架,有需求提出打开的菜单tab可以实现拖拽的功能,于是乎找度娘搜刮了一通,找到了想要的结果,参考地址。但是这个参考地址有漏洞,拖拽是实现了,只是拖拽后对应的页面没有切换。所以我后续还做了一些优化,具体实现如下:
首先安装sortablejs
npm install sortablejs --save
接下来看看代码都改了什么吧,首先先要搞清楚在哪里改代码:
安装完sortablejs后,接下来所有的操作都需要在src-->layout-->TagsView-->index.vue中进行修改
图中可以看到,首先第一步导入sortablejs
import Sortable from 'sortablejs'
接下来代码中只需添加如下方法即可:
代码如下:
/**
* 拖拽方法(页面上方打开的菜单,添加拖拽事件)
*/
rowDrop() {
const el = document.querySelector('.tags-view-wrapper .el-scrollbar__wrap .el-scrollbar__view'); // 找到想要拖拽的那一列
const _this = this;
Sortable.create(el, {
onEnd({ newIndex, oldIndex }) {
// oldIIndex拖放前的位置, newIndex拖放后的位置 //visitedViews为遍历的tab签
const currRow = _this.visitedViews.splice(oldIndex, 1)[0] // 鼠标拖拽当前的el-tabs-pane
_this.visitedViews.splice(newIndex, 0, currRow) // tableData 是存放所以el-tabs-pane的数组
// 拖拽完成后,如果当前路由不等于拖拽路由,则跳转到当前拖拽路径
if (_this.$route.path !== currRow.path) {
_this.$router.push({ path: currRow.path });
}
}
});
},
就是这么简单,一个拖拽的效果就实现了。
当然,有些朋友可能想看整个index的完整代码,那也可以附上如下完整代码,,,但是实际上只需添加上面的方法即可。
完整代码:
<template>
<div class="tags-view-container">
<scroll-pane ref="scrollPane" class="tags-view-wrapper">
<router-link
v-for="tag in visitedViews"
ref="tag"
:key="tag.path"
:class="isActive(tag)?'active':''"
:to="{ name: tag.name, query: tag.query, fullPath: tag.fullPath, params: tag.params }"
tag="span"
class="tags-view-item"
@click.middle.native="closeSelectedTag(tag)"
@contextmenu.prevent.native="openMenu(tag,$event)"
>
{{ generateTitle(tag.title) }}
<span v-if="!tag.meta.affix" class="el-icon-close" @click.prevent.stop="closeSelectedTag(tag)" />
</router-link>
</scroll-pane>
<ul v-show="visible" :style="{left:left+'px',top:top+'px'}" class="contextmenu">
<li @click="refreshSelectedTag(selectedTag)">
{{ $t('tagsView.refresh') }}
</li>
<li v-if="!(selectedTag.meta&&selectedTag.meta.affix)" @click="closeSelectedTag(selectedTag)">
{{ $t('tagsView.close') }}
</li>
<li @click="closeOthersTags">
{{ $t('tagsView.closeOthers') }}
</li>
<li @click="closeAllTags(selectedTag)">
{{ $t('tagsView.closeAll') }}
</li>
</ul>
</div>
</template>
<script>
import ScrollPane from './ScrollPane'
import Sortable from 'sortablejs'
import { generateTitle } from '@/utils/i18n'
import path from 'path'
export default {
name: 'TagsView',
components: { ScrollPane },
data() {
return {
visible: false,
top: 0,
left: 0,
selectedTag: {},
affixTags: []
}
},
computed: {
visitedViews() {
return this.$store.state.tagsView.visitedViews
},
routes() {
return this.$store.state.permission.routes
}
},
watch: {
$route() {
this.addTags()
this.moveToCurrentTag()
},
visible(value) {
if (value) {
document.body.addEventListener('click', this.closeMenu)
} else {
document.body.removeEventListener('click', this.closeMenu)
}
}
},
mounted() {
this.initTags()
this.addTags()
this.rowDrop()
},
methods: {
/**
* 拖拽方法(页面上方打开的菜单,添加拖拽事件)
*/
rowDrop() {
const el = document.querySelector('.tags-view-wrapper .el-scrollbar__wrap .el-scrollbar__view'); // 找到想要拖拽的那一列
const _this = this;
Sortable.create(el, {
onEnd({ newIndex, oldIndex }) {
// oldIIndex拖放前的位置, newIndex拖放后的位置 //visitedViews为遍历的tab签
const currRow = _this.visitedViews.splice(oldIndex, 1)[0] // 鼠标拖拽当前的el-tabs-pane
_this.visitedViews.splice(newIndex, 0, currRow) // tableData 是存放所以el-tabs-pane的数组
// 拖拽完成后,如果当前路由不等于拖拽路由,则跳转到当前拖拽路径
if (_this.$route.path !== currRow.path) {
_this.$router.push({ path: currRow.path });
}
}
});
},
generateTitle, // generateTitle by vue-i18n
isActive(route) {
return route.path === this.$route.path
},
filterAffixTags(routes, basePath = '/') {
let tags = []
routes.forEach(route => {
if (route.meta && route.meta.affix) {
const tagPath = path.resolve(basePath, route.path)
tags.push({
fullPath: tagPath,
path: tagPath,
name: route.name,
meta: { ...route.meta }
})
}
if (route.children) {
const tempTags = this.filterAffixTags(route.children, route.path)
if (tempTags.length >= 1) {
tags = [...tags, ...tempTags]
}
}
})
return tags
},
initTags() {
const affixTags = this.affixTags = this.filterAffixTags(this.routes)
for (const tag of affixTags) {
// Must have tag name
if (tag.name) {
this.$store.dispatch('tagsView/addVisitedView', tag)
}
}
},
addTags() {
const { name } = this.$route
if (name) {
this.$store.dispatch('tagsView/addView', this.$route)
}
return false
},
moveToCurrentTag() {
const tags = this.$refs.tag
this.$nextTick(() => {
for (const tag of tags) {
if (tag.to.path === this.$route.path) {
this.$refs.scrollPane.moveToTarget(tag)
// when query is different then update
if (tag.to.fullPath !== this.$route.fullPath) {
this.$store.dispatch('tagsView/updateVisitedView', this.$route)
}
break
}
}
})
},
refreshSelectedTag(view) {
this.$store.dispatch('tagsView/delCachedView', view).then(() => {
const { fullPath } = view
this.$nextTick(() => {
this.$router.replace({
path: '/redirect' + fullPath
})
})
})
},
closeSelectedTag(view) {
this.$store.dispatch('tagsView/delView', view).then(({ visitedViews }) => {
if (this.isActive(view)) {
this.toLastView(visitedViews)
}
})
},
closeOthersTags() {
this.$router.push(this.selectedTag)
this.$store.dispatch('tagsView/delOthersViews', this.selectedTag).then(() => {
this.moveToCurrentTag()
})
},
closeAllTags(view) {
this.$store.dispatch('tagsView/delAllViews').then(({ visitedViews }) => {
if (this.affixTags.some(tag => tag.path === view.path)) {
return
}
this.toLastView(visitedViews)
})
},
setting() {
this.$confirmBox(
`${this.$t('tagsView.content1')}<br>
${this.$t('tagsView.content2')}<br>
${this.$t('tagsView.content3')}<br>`,
this.$t('tagsView.setting'),
{ dangerouslyUseHTMLString: true, showClose: false }
).then(_ => {
localStorage.setItem('visitedViewsSetting', 'autoClose')
}).catch(_ => {
localStorage.setItem('visitedViewsSetting', 'manualClose')
})
},
toLastView(visitedViews) {
const latestView = visitedViews.slice(-1)[0]
if (latestView) {
this.$router.push(latestView)
} else {
// You can set another route
this.$router.push('/')
}
},
openMenu(tag, e) {
const menuMinWidth = 105
const offsetLeft = this.$el.getBoundingClientRect().left // container margin left
const offsetWidth = this.$el.offsetWidth // container width
const maxLeft = offsetWidth - menuMinWidth // left boundary
const left = e.clientX - offsetLeft + 15 // 15: margin right
if (left > maxLeft) {
this.left = maxLeft
} else {
this.left = left
}
this.top = e.clientY - 20
this.visible = true
this.selectedTag = tag
},
closeMenu() {
this.visible = false
}
}
}
</script>
<style lang="scss" scoped>
.tags-view-container {
height: 34px;
margin: 0 20px 0 50px;
background: #0c161e;
border-bottom: 1px solid #2674b2;
.tags-view-wrapper {
.tags-view-item {
display: inline-block;
position: relative;
cursor: pointer;
height: 26px;
line-height: 26px;
border: 1px solid #295477;
color: #ccc;
background: #0c161e;
padding: 0 8px;
font-size: 12px;
margin-left: 5px;
margin-top: 4px;
&:first-of-type {
margin-left: 15px;
}
&:last-of-type {
margin-right: 15px;
}
&.active {
background-color: #295477;
color: #fff;
border-color: #295477;
&::before {
content: '';
background: #fff;
display: inline-block;
width: 8px;
height: 8px;
border-radius: 50%;
position: relative;
margin-right: 2px;
}
}
}
}
.contextmenu {
margin: 0;
background: #fff;
z-index: 100;
position: absolute;
list-style-type: none;
padding: 5px 0;
border-radius: 4px;
font-size: 12px;
font-weight: 400;
color: #333;
box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, .3);
li {
margin: 0;
padding: 7px 16px;
cursor: pointer;
&:hover {
background: #eee;
}
}
}
}
</style>
<style lang="scss">
//reset element css of el-icon-close
.tags-view-wrapper {
.tags-view-item {
.el-icon-close {
width: 16px;
height: 16px;
vertical-align: 2px;
border-radius: 50%;
text-align: center;
transition: all .3s cubic-bezier(.645, .045, .355, 1);
transform-origin: 100% 50%;
&:before {
transform: scale(.6);
display: inline-block;
vertical-align: -3px;
}
&:hover {
background-color: #b4bccc;
color: #fff;
}
}
}
}
</style>