我使用Vue.js modal在我的 Vue 应用程序中。它是 Vue 组件的一部分。模板部分仅包含模态:
<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>
我需要访问 DOM 元素才能使用 Rangy库并突出显示 my-div
中的一些文本。但每当我尝试在方法中获取它时,我都会得到 undefined
或 null
,具体取决于我使用纯 JS 还是 Vue 引用:
console.log(this.$refs.myDiv); // undefined
console.log(document.getElementById('my-div'); // null
当我执行 console.log(this.$refs
) 时,我在 refs
属性内得到 myDiv
。但是,当我在 console.log
之后直接使用 debugger
停止代码执行时,refs
似乎是空的。
这里有什么问题吗?我该如何获取对我需要修改的 div
的引用?
编辑:这是一个更完整的代码片段
<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>
最佳答案
只要模式关闭,您就无法访问模式内的内容。但是,当模式切换为可见时,vue-js-modal
组件会发出“打开”事件。您可以在模态打开并完成渲染时调用代码。
<modal
name='edit-exercise-modal'
@opened="onModalOpened"
:draggable='true'
height='auto'
>
...
</modal>
关于JavaScript:在 Vue.js 模式中获取 DOM 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57481048/