Vue POC中集成jQuery Draggable实现拖拽功能失效问题求助
Hey there! Let's get your drag-and-drop functionality up and running. The core issue here is that even though you've installed jquery-ui, you haven't imported the specific drag-and-drop widgets your component needs—so jQuery doesn't recognize the draggable() and droppable() methods yet. Here's how to fix this step by step:
1. Import the Required jQuery UI Widgets
In your component's <script> section, add imports for the draggable and droppable modules from jquery-ui. This loads only the parts you need, keeping your code efficient:
import $ from 'jquery'; // Add these two lines to load the drag-and-drop widgets import 'jquery-ui/ui/widgets/draggable'; import 'jquery-ui/ui/widgets/droppable';
2. (Optional but Recommended) Use Vue Refs for Reliable DOM Targeting
Class selectors like $('.image') can sometimes pick up unintended elements from other components in Vue. A cleaner, more Vue-native approach is to use ref attributes to target elements directly in your component:
<template> <div> <h1>Drag the images into the box</h1> <div class="images"> <img ref="dragImage1" class="image" :src="image1" alt=""> <div ref="dropBox" class="box"></div> <img ref="dragImage2" class="image" :src="image2" alt=""> </div> <!-- Rest of your template --> </div> </template> <script> import $ from 'jquery'; import 'jquery-ui/ui/widgets/draggable'; import 'jquery-ui/ui/widgets/droppable'; export default { // ... your data and methods mounted(){ // Initialize draggable elements using refs $(this.$refs.dragImage1).draggable({ revert: true }); $(this.$refs.dragImage2).draggable({ revert: true }); // Initialize droppable box using ref $(this.$refs.dropBox).droppable({ hoverClass: 'drop-hover', drop: function(){ console.log('-= dropped =-') } }); } } </script>
3. Add Visual Feedback for Hover State
You defined the drop-hover class but didn't add styles for it. Let's fix that to give users clear visual feedback when dragging over the box:
.box.drop-hover { border-color: #2196F3; background-color: rgba(33, 150, 243, 0.1); }
4. Verify the Setup
To confirm the widgets are loaded correctly, add a quick console log in your mounted hook:
mounted(){ console.log($.fn.draggable); // Should log a function if imports are working // ... rest of your code }
If this logs undefined, double-check your import paths for typos.
After making these changes, your images should be draggable, and the box should register drops with the console message appearing as expected.
内容的提问来源于stack exchange,提问作者Pimv_h

