那你能给我写个demo出来吗
时间: 2023-08-03 19:03:01 浏览: 43
当然可以,以下是一个简单的Vue2拖拉拽动态配置表单的demo,供你参考:
```vue
<template>
<div class="form-builder">
<draggable v-model="fields" :options="dragOptions" class="field-list">
<div v-for="(field, index) in fields" :key="index" class="form-field">
<div class="form-field-header">
<span>{{ field.label }}</span>
<button @click="deleteField(index)">删除</button>
</div>
<div class="form-field-body">
<component :is="field.type" v-model="field.value" />
</div>
</div>
</draggable>
<button @click="addField">添加字段</button>
</div>
</template>
<script>
import draggable from 'vuedraggable';
export default {
name: 'FormBuilder',
components: {
draggable,
},
data() {
return {
fields: [],
dragOptions: {
animation: 200,
group: 'form-fields',
disabled: false,
ghostClass: 'form-field-dragging',
},
};
},
methods: {
addField() {
this.fields.push({
type: 'text-field',
label: '新字段',
value: '',
});
},
deleteField(index) {
this.fields.splice(index, 1);
},
},
computed: {
fieldTypes() {
return {
'text-field': () => import('./components/TextField.vue'),
'number-field': () => import('./components/NumberField.vue'),
// 其他类型的表单字段和组件
};
},
},
watch: {
fields: {
handler(fields) {
console.log(fields); // 在这里可以监听表单字段的变化
},
deep: true,
},
},
};
</script>
```
上述代码中,我们使用了Vue-Draggable插件来实现拖拽功能,通过v-for指令和computed属性来渲染表单字段和控件,使用v-model指令来绑定表单字段的值,使用动态组件来根据字段类型渲染不同的表单控件,使用watch属性来监听表单字段的变化,使用methods属性来定义添加和删除表单字段的方法。
在实际开发中,你需要根据自己的需求来进行调整和扩展。