首页 > 解决方案 > VueJS 和“vue-markdown”,当触发 `rendered` 事件时 DOM 仍未准备好

问题描述

我有这个:

<vue-markdown :source="content" v-on:rendered="afterRenderContent"></vue-markdown>

但是当afterRenderContent触发该方法时,HTML 元素仍然不存在。

我想在渲染后进行 DOM HTML 元素操作,但我不能。等待DOM准备好的正确方法是什么?

我试图创建一个 JSFiddle 来重现该问题,但看起来 CDN 库没有正确加载:

标签: javascriptvue.jsevents

解决方案


Try moving your afterRenderContent method to the mounted lifecycle hook. You can only manipulate DOM elements after the component has been mounted.

mounted() {
    this.afterRenderContent()
}

More on lifecycle methods here: https://vuejs.org/v2/guide/instance.html#Lifecycle-Diagram.

I notice you are also using some vanilla javascript, in your js fiddle, refs can be used in vue to access DOM elements in a more intuitive fashion .

<template>
    <h1 ref="header-one">Header One</h1>
</template>

// in your component method or mounted hook
mounted() {

    // access the header element 
    this.$refs['header-one']
}

EDIT: On a deeper dive Perhaps this might work, hooking into the mounted lifecycle method from a child component.

<vue-markdown :source="content" @hook:mounted="afterRenderContent"</vue-markdown>

Decent blog on how to use refs with vue here https://blog.logrocket.com/how-to-use-refs-to-access-your-application-dom-in-vue-js/


推荐阅读