I use Vue.js modal inside my Vue app. It's part of a Vue component. The template part consists of the modal only:
<template>
<!-- Modal: Edit exercise -->
<modal name='edit-exercise-modal'
:draggable='true'
height='auto'>
<form @submit.prevent='storeEdits'>
<div ref='myDiv'>Some text</div>
<!-- Also tried:
<div id='my-div'>Some text</div>
-->
</form>
</modal>
</template>
I need to access DOM elements to user the Rangy library and highlight some text inside my-div. But whenever I try to get it in a method, I get undefined or null instead, depending on whether I use pure JS or Vue refs:
console.log(this.$refs.myDiv); // undefined
console.log(document.getElementById('my-div'); // null
When I do console.log(this.$refs), I get myDiv inside the refs property. But when I stop code execution with debugger directly after console.log, refs seems to be empty.
What's the problem here? What can I do to get a reference to the div I need to modify?
edit: Here's a more complete snippet
<template>
<!-- Modal: Edit exercise -->
<modal name='edit-exercise-modal'
:draggable='true'
height='auto'>
<form @submit.prevent='storeEdits'>
<div ref='myDiv'>Some text</div>
<!-- Also tried:
<div id='my-div'>Some text</div>
-->
</form>
</modal>
</template>
<script>
import Vue from 'vue';
import VModal from 'vue-js-modal';
Vue.use(VModal);
import rangy from 'rangy';
import 'rangy/lib/rangy-classapplier';
export default {
props: [ 'exercise' ],
/**********************************************
********************* Data ********************
**********************************************/
data: function() {
return {
selected: [],
category_id: undefined,
text: undefined,
mistakes: undefined
};
},
/**********************************************
******************** Methods ******************
**********************************************/
methods: {
sampleMethod: function() {
console.log(this.$refs.textWithMistakes);
console.log(document.getElementById('text-with-mistakes'));
}
},
/**********************************************
******************* Watchers ******************
**********************************************/
watch: {
/**
* Sets up and shows modal when exercise data is loaded from parent.
*/
exercise: function() {
this.category_id = this.exercise.category_id;
this.text = this.exercise.text;
this.mistakes = this.exercise.mistakes;
this.$modal.show('edit-mistakes-exercise-modal');
// Not working
this.applyClass(sampleMethod);
// Working, but not a way I'd like to go
setTimeout(() => {
this.applyClass(sampleMethod);;
}, 3000);
}
}
}
</script>
<div ref='myDiv>console.log$refs. It would be very helpful to us if you can provide snippet of code where you log refs along with the modal component.setTimeout, but that feels like a hacky solution.