效果展示
效果说明
点击左侧的课程并进行拖拽,拖拽到要开设本课程的地方然后松手,即可将本节课设置为当前所拖拽的科目并且背景色为当前科目的背景色,当多次拖拽到同一节课的时候将会实现后者覆盖前者的效果。
效果实现代码
第一步:创建项目
yarn create vite demo1
第二步:安装项目所需要的依赖
yarn
yarn add vue-router
yarn add sass sass-loader
yarn add path
第三步:配置别名@
vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue()
],
resolve: {
alias: {
'@': path.resolve(__dirname, 'src')
}
}
})
第四步:配置路由文件
src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
const routes = [
{
path: '/',
component: () => import('@/views/Drag.vue')
}
]
const route = createRouter({
history: createWebHistory(),
routes
})
export default route
第五步:引用路由文件
main.js
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from './router'
createApp(App).use(router).mount('#app')
第六步:创建Drag.vue文件,并编写效果代码
src/views/Drag.vue
<template>
<div class="box">
<div>
<!-- draggable="true"将元素变为可拖动的 -->
<div
class="subject"
:style="{ backgroundColor: item.bgColor }"
v-for="item in subjects"
:key="item.id"
draggable="true"
@dragstart="handleDragStart(item)"
>
{{ item.name }}
</div>
</div>
<div>
<table border="1" cellspacing="0" width="500" height="500">
<caption>
课程表
</caption>
<tr>
<th colspan="2"></th>
<th v-for="week in weeks" :key="week">{{ week }}</th>
</tr>
<tr v-for="r in 8" :key="r" align="center">
<td v-if="r < 5 && r === 1" rowspan="4">上午</td>
<td v-else-if="r === 5" rowspan="4">下午</td>
<td>{{ parts[r - 1] }}</td>
<td
@dragover.prevent
@drop="handleDrop($event)"
v-for="d in 5"
:key="d"
></td>
</tr>
</table>
</div>
</div>
</template>
<script setup>
import { ref } from "vue";
const subjects = [
{ id: 1, name: "语文", bgColor: "rgb(102, 233, 251)" },
{ id: 2, name: "数学", bgColor: "rgb(242, 149, 123)" },
{ id: 3, name: "英语", bgColor: "rgb(141, 220, 39)" },
{ id: 4, name: "物理", bgColor: "rgb(211, 220, 39)" },
{ id: 5, name: "化学", bgColor: "rgb(230, 181, 111)" },
{ id: 6, name: "生物", bgColor: "rgb(102, 110, 251)" },
{ id: 7, name: "地理", bgColor: "rgb(223, 142, 213)" },
{ id: 8, name: "历史", bgColor: "rgb(242, 233, 123)" },
{ id: 9, name: "政治", bgColor: "rgb(197, 167, 180)" },
];
const weeks = ["星期一", "星期二", "星期三", "星期四", "星期五"];
const parts = [
"第一节",
"第二节",
"第三节",
"第四节",
"第五节",
"第六节",
"第七节",
"第八节",
];
const classObj = ref({ id: "", name: "", bgColor: "" });
const handleDragStart = (item) => {
classObj.value = item;
};
const handleDrop = (e) => {
e.target.textContent = classObj.value.name;
e.target.style.backgroundColor = classObj.value.bgColor;
};
</script>
<style lang="scss" scoped>
.box {
display: flex;
user-select: none;
}
.subject {
margin: 10px;
padding: 20px 10px;
width: 100px;
text-align: center;
border-radius: 20px;
}
table {
margin-top: 20px;
margin-left: 50px;
caption {
font-size: 30px;
}
}
</style>
通过以上代码即可实现展示效果