I have integrated the Vue.js modal into my Vue app using a Vue component. The template section of this component includes the modal itself:
<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 am trying to access DOM elements in order to use the Rangy library and highlight specific text inside my-div
. However, every time I attempt to retrieve it using a method, I receive either undefined
or null
, depending on whether I utilize pure JavaScript or Vue refs:
console.log(this.$refs.myDiv); // undefined
console.log(document.getElementById('my-div'); // null
Upon inspecting with console.log(this.$refs)
, I can see myDiv
under the refs
property. Nevertheless, when I pause code execution using debugger
immediately after console.log
, it appears that refs
is empty.
What could be causing this issue? How can I successfully reference the desired div
for modification?
Edit: Here's an extended code 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>