引自免费微信小程序:皆我百晓生
在Vue.js中,如果你想要将上述的复合型输入框(包含el-input 和 el-select)实现可拖拽功能,可以借助第三方库Sortablejs。首先你需要安装sortablejs和它的Vue插件vue-sortablejs。以下是详细的步骤:
- 安装依赖:
npm install sortablejs --save
npm install vue-sortablejs --save
- 在项目中引入并使用它们:
在入口文件(通常是
main.js)中引入:
import Sortable from 'sortablejs';
import VueSortable from 'vue-sortablejs';
Vue.use(VueSortable, { Sortable });
- 创建一个Vue组件,例如叫做
DraggableInput.vue,并将复合型输入框与拖拽功能结合在一起:
<template>
<div class="draggable-input-container" v-bind:style="{ display: 'flex', flexDirection: 'column' }" @click="onClick" ref="container">
<el-input
:disabled="item.disabled"
v-model="input3"
class="input-with-select"
>
<el-select
v-model="select"
slot="prepend"
:disabled="item.disabled"
placeholder="请选择"
>
<el-option
v-for="(option, index) in options"
:key="index"
:label="option.label"
:value="option.value"
></el-option>
</el-select>
</el-input>
<!-- 添加额外的元素,用于拖拽 -->
<span v-if="!item.disabled" @mousedown="startDrag" class="handle">☰</span>
</div>
</template>
<script>
export default {
name: "DraggableInput",
props: {
item: {
type: Object,
required: true,
default: () => ({ disabled: false, type: 'input' }),
},
options: {
type: Array,
required: true,
default: () => [
{ label: "餐厅名", value: "1" },
{ label: "订单号", value: "2" },
{ label: "用户电话", value: "3" },
],
},
},
methods: {
onClick(event) {
event.stopPropagation();
},
startDrag(event) {
this.$sortableStart(this.$refs.container, event);
},
},
};
</script>
<style scoped>
.handle {
cursor: move;
width: 20px;
height: 20px;
background-color: #ccc;
border-radius: 50%;
position: absolute;
top: -10px;
left: calc(50% - 10px);
}
</style>
- 然后在父组件中使用这个新的
DraggableInput组件:
<template>
<div id="app">
<draggable-input
v-for="(item, index) in items"
:key="index"
:item="item"
:options="options"
/>
</div>
</template>
<script>
import DraggableInput from './components/DraggableInput.vue';
export default {
components: {
DraggableInput,
},
data() {
return {
items: [
{ type: 'input', value: '', disabled: false },
{ type: 'select', value: '', disabled: false },
],
options: [
{ label: "餐厅名", value: "1" },
{ label: "订单号", value: "2" },
{ label: "用户电话", value: "3" },
],
};
},
};
</script>
以上代码中,我们创建了一个名为DraggableInput的新组件,它包含了可选的el-select和el-input。为了实现拖拽功能,我们在每个输入框前面添加了一个可点击的小图标,通过监听鼠标按下事件来启动拖拽。我们还为容器添加了CSS样式,使其显示为垂直布局。
注意:这个例子使用了VueSortable提供的 $sortableStart 方法来启动拖拽。要让整个列表支持拖拽排序,你需要在父组件中使用Sortable实例,并将子组件的容器作为参数传递给它。这超出了当前问题的范围,但你可以在DraggableInput组件的外部实现这一功能。如果你需要这部分的代码,我可以提供完整的示例。