本文主要是介绍记录一个拖拽组件vue3+ts,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
记录一个拖拽组件vue+ts
“vue”: “^3.0.0”
“typescript”: “~4.1.5”
我这个是vue 3的最高版本,可以使用defineModel
父组件
<h1>props传值</h1><ModuleOrder v-model:orderList="orderList" v-model:defaultList="defaultList" ></ModuleOrder><button @click="setOrderData(1)" >新增一条</button><button @click="setOrderData(2)" >删除一条</button><br>import ModuleOrder from './components/moduleOrder.vue'components:{ModuleOrder},// props传值const orderList:number[] = reactive([1,2,3,4,5])const defaultList:number[] = reactive([1,2,3,4,5])const setOrderData = (type:number)=>{if (type === 1){orderList.push(6)defaultList.push(6)}else{orderList.pop()defaultList.pop()}}
子组件moduleOrder.vue
<template><button @click="reserData()" >重置</button><ul><li v-for="(item,index) in orderList" :key="item" draggable="true" @dragstart="lDragStart(index)" @dragover.prevent @drop.prevent="lDrop(index)" >{{ item }}</li></ul>
</template><script setup lang="ts" >
import {defineModel,onMounted,ref} from 'vue'
const defaultList = defineModel<number[]>("defaultList")
const orderList = defineModel<number[]>("orderList")
// const [defaultList,orderList] = defineModel<number[]>()
const startIndex = ref<number | null>(null)
const reserData = ()=>{orderList.value = defaultList.value
}
function lDragStart(index:number){startIndex.value = index
}
function lDrop(index:number){if (startIndex.value && orderList.value){const startItem:number = orderList.value[startIndex.value]orderList.value[startIndex.value] = orderList.value[index]orderList.value[index] = startItem}
}
</script>
可以用const [defaultList,orderList] = defineModel<number[]>()结构出变量,对于ts有个问题,<number[]>只能给第一个变量添加类型,第二个对象是Record
const defaultList: ModelRef<number[] | undefined, string>
const orderList: Record<string, true | undefined>
如果vue版本低于3.4,不支持defineModel就只能用defineProps和defineEmits
const props = defineProps(['orderList','defaultList'])
const emit = defineEmits(['update:orderList','update:defaultList'])const orderList=ref([]);
const defaultList=ref([]);watch([()=>props.orderList,()=>props.defaultList],()=>{orderList.value = props.orderListdefaultList.value = props.defaultList
},{deep:true,immediate:true})emit('update:LsitemList',orderList.value)
emit('update:defaultList',defaultList.value)
这篇关于记录一个拖拽组件vue3+ts的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!