问题描述
我正在尝试使用Vue.js访问DOM。我正在mount()生命周期内编写代码,但是没有得到任何结果。
使用香草JavaScript的代码可以正常工作。
我正在使用v-html指令在span标签内插入html。
var delayedChangeEvent = null;
function invokeConditionally() {
delayedChangeEvent = setTimeout(function(){
var _formId = $('.userCodeInput').closest("form").attr('id');
var _source = $('.userCodeInput').attr('id');
var _update = [$('.internationalEntryGroup').attr('id'),$('.applianceEntryGroup').attr('id'),$('.drugEntryGroup').attr('id'),$('.userAmountSection').attr('id'),$('.overrideuserAmountSection').attr('id'),$('.addButtonSection').attr('id'),$('.userCodeSectionMsg').attr('id')];
PrimeFaces.ajax.Request.handle({
formId: _formId,source: _source,update: _update,event: 'itemSelect'
});
},500);
}
然后进入已安装的生命周期
<span class="email" v-html="text"></span>
如何在Vue.js中访问DOM?
解决方法
您需要知道在Vue.js中看到的HTML标记或React实际上不是HTML标记。它被解析为纯javascript对象,虚拟DOM。
您需要等到vuejs呈现其虚拟DOM。您可以使用this.$nextTick()
mounted() {
this.$nextTick(() => {
let images = document.getElementsByClassName(
"mcnImageCardBottomImageContent"
);
console.log(images);
// It is returning an empty array
})
}
,
这样的作品行吗? :)
mounted() {
document.onreadystatechange = () => {
if (document.readyState === "complete") {
console.log("Page loaded");
// Do stuff here
}
};
}