D
D
Dmitry2017-08-16 13:54:56
JavaScript
Dmitry, 2017-08-16 13:54:56

How to correctly initialize a Vue component after an element appears in the DOM?

I have a page that has a button that opens a modal window.
The content of the modal window is loaded via AJAX and the content of the response (HTML) is inserted into the DOM.
This HTML contains some Vue components (comment component).
How to correctly instantiate this Vue component?

Current implementation
import Vue from "vue";
import Comments from "./components/comments.vue";
import {listenDomForElement} from "./../../common/helpers";

'use strict';

/** Variables */
let commentsBlockVm,
    vueElement = '#comments-block';

/** Комментарии */
commentsBlockVm = new Vue({
    name: 'comments-block',
    components: {Comments},
});

/** Специальный хелпер, слушающий DOM (MutationObserver) */
listenDomForElement(vueElement, function (element) {
    // Коллбэк исполнится, когда элемент появится в DOM
    // Маунтим Vue инстанс к нужному элементу
    commentsBlockVm.$mount(element);
    // Без этого компонент нормально не работает
    window.commentsBlockVm = commentsBlockVm;
});

export {commentsBlockVm}


DevTools is empty.
drHtLtA.png
With the current implementation in Vue DevTools, I don't see this component, probably due to the fact that devtools is only initialized on page load.
How to solve this problem correctly or at least make devtools see this component?
Doki read, the only thing that is close to the solution is the life cycle hooks, but I'm not sure.
Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2017-08-16
@another_dream

The problem was solved by including the JS file directly into the HTML, which arrives along with the content of the modal window.
Apparently, it should have been done right away, although it looks rude.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question