Skip to content

Is element.__vue__ save to use? #5621

@jantimon

Description

@jantimon

Is there a clean way to get the current vue instance from a given DOM node or is it even future save to access element.__vue__?

The use case is the integration with a large famous enterprise content management system where we would like to build up all content elements out of vue components.
Unfortunately the CMS ships with javascript code which can't be changed without too high efforts.
These third party scripts allow authors of the cms to use drag'n'drop to place new content element (e.g. a carousel or a teaser) to the page.
After the drag'n'drop happened an event is fired which we would like to bind on and reinitialize all new placed inline template elements.

We managed to come up with a hack but maybe there is a better solution for this use case:
https://jsfiddle.net/5vxwr34o/

/**
 * Content change handler
 */
function handleContentChange() {
  const inlineTemplates = document.querySelector('[inline-template]');
  for (var inlineTemplate of inlineTemplates) {
    processNewElement(inlineTemplate);
  }
}

/**
 * Tell vue to initialize a new element
 */
function processNewElement(element) {
  const vue = getClosestVueInstance(element);
  new Vue({
    el: element,
    data: vue.$data
  });
}

/**
 * Returns the __vue__ instance of the next element up the dom tree
 */
function getClosestVueInstance(element) {
  if (element) {
    return element.__vue__ || getClosestVueInstance(element.parentElement);
  }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions