I have a problem that I can't get my head around. I am using Three.js in my web app and I want to add a loading spinner when I upload a file. For that I created a component with the loading spinner, and display it with v-if when the file gets loaded.
Strangely enough, this does not work, even though the value "loading" is true when logged from within the function (when I log it after the file is loaded it is false again without changing it).
The code:
<template>
<div class="button-draw-container">
<input id="file-input" name="button-upload" type="file" @click="importFile"/>
</div>
<div v-if="loading" id="wrapper-loader">
<Loader/>
</div>
</template>
<script>
export default {
components: {
Loader
},
data() {
return {
loading: false,
}
},
methods: {
importFile() {
var fileInput = document.querySelector("#file-input");
var cores = [];
var outline;
fileInput.addEventListener("change", function(event) {
//This is the part that's not working
this.loading = true;
console.log(this.loading)
const reader = new FileReader();
reader.addEventListener("load", function(event) {
const contents = event.target.result;
const loader = new Rhino3dmLoader();
loader.setLibraryPath( 'https://cdn.jsdelivr.net/npm/three@0.138.2/examples/jsm/libs/rhino3dm/' );
loader.parse( contents, function( object ) {
for (let i = 0; i < object.children.length; i++) {
if(object.children[i].userData.attributes.layerIndex == 1) {
cores.push(object.children[i].geometry);
}
else if(object.children[i].userData.attributes.layerIndex == 2) {
outline = object.children[i].geometry;
}
}
} );
});
reader.readAsArrayBuffer( this.files[0] );
})
},
}
</script>
The problem was that the scope of "this" is within the function block, meaning that this is no longer a reference to the Vue instance.
Using an arrow function which has no lexical scope and changing the last line to reader.readAsArrayBuffer( fileInput.files[0] ); did the job.