0👍
✅
I think you are over complicating things, it is better to avoid DOM manipulations unless it is strictly needed.
It is a better solution to add inline styles, or switch classes on the vue templates with reactive data instead of adding and removing classes directly on the DOM as you’d do with the old Jquery.
This is reactive, easy and cheap to control:
<div :style="{ background: box1}"></div>
I’ve rewrited your code following this rules:
<template>
<div>
<div class="box-flex">
<div class="box" @dragover.prevent @drop="drop" id="box-1" :style="{ background: box1}"></div>
<div class="box" @dragover.prevent @drop="drop2" id="box-2" :style="{ background: box2}"></div>
<div class="box" :style="{ background: box3}"></div>
</div>
<!-- the elements I want to drag -->
<div v-for="(flower, i) in flowers" :key="i">
<div>
<p>{{ flower.type }}</p>
<p v-for="(color, j) in flower.colors" :key="j">
<span
:id="color"
:draggable="true"
@dragstart="dragStart"
@dragover.stop
>{{ color }}</span>
</p>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'Intro',
components: {
},
data() {
return {
//flowers
flowers: [
{
type: "Cosmos",
colors: ["red", "yellow", "orange", "black", "pink", "white"]
},
],
box1: 'white',
box2: 'white',
box3: 'white',
};
},
methods: {
dragStart(e) {
let target = e.target;
e.dataTransfer.setData("color_id", target.id);
e.dataTransfer.setData("box_el", target);
},
//first container drop
drop(e) {
this.box1 = e.dataTransfer.getData("color_id");
if ( this.box1 == 'red' && this.box2 == 'yellow') {
this.box3 = 'orange'
}
else {
this.box3 = 'white'
}
},
//second container drop
drop2(e) {
this.box2 = e.dataTransfer.getData("color_id");
if ( this.box1 == 'red' && this.box2 == 'yellow') {
this.box3 = 'orange'
}
else {
this.box3 = 'white'
}
}
},
};
</script>
<style>
.box-flex {
height: 50px;
display: flex;
justify-content: space-around;
align-items: center;
}
.box,
.box-1,
.box-2 {
width: 20px;
height: 20px;
border: 2px solid black;
}
.Cosmos-red {
background: red;
}
.Cosmos-yellow {
background: yellow;
}
.Cosmos-orange {
background: orange;
}
</style>
Source:stackexchange.com