I am attempting to make use of the dataset
attributes of elements, to enable data to be transferred from one item to another during a drag/drop process. But I am having some odd results depending on how Vues' v-if
condition is used. The code below works as expected: if you click the 'move' button, then look at the underlying elements' datasets using the 'inspect' button, the dataset for the second item changes.....
<script setup>
import { onMounted,ref,reactive } from 'vue'
const thisData = reactive(['AAA','BBB','CCC','DDD','EEE'])
var items = [];
var moves = 0;
onMounted(() => {
items= document.querySelectorAll('.swappable') ;
inspect();
});
function inspect() {
for (let n=0; n < 5; n++) {
let data = items[n].dataset.transfer;
const elem = document.getElementById(idString(n+100));
elem.innerText = 'id: ' + items[n].id + ' :' + data ;
}
}
function move() {
thisData[1] = thisData[0];
++moves;
}
function localTest(x) {
return x > 2;
}
function globalTest(chip) {
return moves > 0;
}
function idString(n) {
return 'btn'+n;
}
function dataTransfer(n) {
return 'data stored: '+n;
}
</script>
<template>
<template v-for="(item,n) in thisData" :key="n" >
<button v-if="localTest(n)" style="background-color: lightblue;" class="swappable"
:data-transfer = dataTransfer(item)
:id=idString(n)
> {{ item }}
</button>
<button v-else style="background-color: lightgreen;" class="swappable"
:data-transfer = dataTransfer(item)
:id=idString(n)
> {{ item}}
</button>
<p :id=idString(n+100) > </p>
</template>
<button @click="inspect()">Inspect Element Data</button >
<p></p>
<button @click="move()">Copy btn 1 to btn 2</button >
</template>
... but if the v-if
test is changed to globalTest(n)
instead of localTest(n)
, the dataset does not change.
My app needs to use a test using a 'global' (a reactive one in fact) but I also need to access the changed dataset.
The effect can be seen here, by editing the v-if
test.