1

I'm trying to create a component that will render elements inside VueJs virtual dom with a Vuex state.

The problem is I get this error but I don't understand why and how to fix it

Avoid using observed data object as vnode data: {"class":"btn btn-default"} Always create fresh vnode data objects in each render!

Inside my Vuex state I store and object where I define the elements properties

{
  type: 'a',
  config: {
    class: 'btn btn-default',
  },
  nestedElements: [
    {
      type: 'span',
      value: 'test',
    },
    {
      type: 'i',
    },
  ],
},

My components code look like

methods: {
  iterateThroughObject(object, createElement, isNestedElement = false) {
    const generatedElement = [],
          nestedElements = [];

    let parentElementConfig = {};

    for (const entry of object) {
      let nodeConfig = {};

      if (typeof entry.config !== 'undefined' && isNestedElement) {
        nodeConfig = entry.config;
      } else if (typeof entry.config !== 'undefined') {
        parentElementConfig = entry.config;
      }

      if (entry.nestedElements) {
        nestedElements.push(this.iterateThroughObject(entry.nestedElements, createElement, true));
      }

      if (!isNestedElement) {
        nodeConfig = parentElementConfig;
      }

      generatedElement.push(createElement(
        entry.type,
        nodeConfig === {} ? entry.value : nodeConfig,
        nestedElements
      ));
    }

    if (isNestedElement) {
      return generatedElement;
    }

    return createElement('ul', generatedElement);
  },
},
render(createElement) {
  const barToolsElements = this.$store.state.titleBar.barToolsElements;

  if (barToolsElements) {
    return this.iterateThroughObject(barToolsElements, createElement);
  }

  return false;
},

The error is produced when I try to pass inside my last generatedElement.push() definition. Because entry.value is {"class":"btn btn-default"}.

I don't understand why it tell me to recreate a fresh Vnode object while this value is used only once.

Did I miss or misunderstand something?

Jérôme
  • 1,966
  • 4
  • 24
  • 48

1 Answers1

0

Might be because you're passing references to objects in your store's state, which might lead inadvertently to their mutation. Try creating deep clones of these objects when you pass them around, like for example ..

nodeConfig = JSON.parse(JSON.stringify(entry.config));

parentElementConfig = JSON.parse(JSON.stringify(entry.config));

nodeConfig === {} ? JSON.parse(JSON.stringify(entry.value)) : nodeConfig,

Husam Ibrahim
  • 6,999
  • 3
  • 16
  • 28