Vue.js学习笔记(8)拖放
小颖在目前负责的项目中,负责给同事提供所需组件,在这期间,我们家大颖姐姐让我 写个拖拽组件,一开始我是用click实现,先将你要拖拽的dom点一下,然后再点你要放的位置,这个dom再通过小颖写的方法,渲染在你要显示的地方,虽然功能实现了,可是没有实现拖拽,我那是点击,所以小颖今天就看了下html5的拖放,然后写了个小示例,希望对大家有所帮助.
小颖是用vue写的嘻嘻,大家要是用js实现的话看看HTML 5 拖放
代码请看这里,当当当当:
html:
<template> <div class='drag-content'> <div class='project-content'> <div class='select-item' draggable='true' @dragstart='drag($event)' v-for='pjdt in projectdatas'>{{pjdt.name}}</div> </div> <div class='people-content'> <div class='drag-div' v-for='(ppindex,ppdt) in peopledata' @drop='drop($event)' @dragover='allowDrop($event)'> <div class='select-project-item'> <label class='drag-people-label'>{{ppdt.name}}:</label> </div> </div> </div> </div> </template>
css代码:
<style scoped> .select-item { background-color: #5bc0de; display: inline-block; text-align: center; border-radius: 3px; margin-right: 10px; cursor:pointer; padding: 6px 20px; color: #fff; } .cursored{ cursor: default; } .project-content,.people-content { margin: 30px 50px; } .people-content { margin-top: 30px; } .drag-div { border: 1px solid #5bc0de; padding:10px; margin-bottom: 10px; width: 800px; cursor: pointer; } .select-project-item { display: inline-block; text-align: center; border-radius: 3px; } .drag-people-label{ margin-bottom:0; padding-right:10px; } </style>
<div class='select-item' draggable='true' @dragstart='drag($event)' v-for='pjdt in projectdatas'>{{pjdt.name}}</div>
在这行代码中小颖在绑定dragstart事件时,drag($event)写法和js写法不一样,如果你在vue中绑定事件时要传 'event',你不能像js那种格式去写 ,比如:@dragstart='drag(event)' 这个写的话你在drag方法中获取到的event是 undefined,因为它把 @dragstart='drag(event)' 中的event当成了一个变量,而该变量并没有在data中定义所以就是 undefined.早上小颖就碰到过此坑.所以切记格式是介个酱紫的: @dragstart='drag($event)'
js代码:
<script> let dom = null export default { components: { }, ready: function() { }, methods: { drag:function(event){ dom = event.currentTarget }, drop:function(event){ event.preventDefault(); event.target.appendChild(dom); }, allowDrop:function(event){ event.preventDefault(); }, }, data() { return { projectdatas:[{ id:1, name:'葡萄', },{ id:2, name:'芒果', },{ id:3, name:'木瓜', },{ id:4, name:'榴莲', }], peopledata:[{ id:1, name:'小颖', },{ id:2, name:'hover', },{ id:3, name:'空巢青年三 ', },{ id:3, name:'一丢丢', }] } } } </script>
页面效果就是介个酱紫的: