Search code examples
vue.jsvuexnuxt.js

dynamically created vue component doesn't have $store paramater how to manually add it at creation time


I'm new to vue/nuxt, and I have ran into an issue where I'm trying to use Vue/Nuxt to dynamically create a vue component on button click with the following code:

async addComponent(componentsItem) {

  var ComponentClass = Vue.component('newFinancials', Financials);
  
  var instance = new ComponentClass({
    propsData: {
      sizeLoc: this.defaultContainer,
      control: componentsItem.componentName,
    }
  });
  var componentContainer = document.getElementById("dragContainer");
  var dummyElement = document.createElement("newComponent");
  dummyElement.setAttribute("id", "newComponent");
  componentContainer.appendChild(dummyElement);
  instance.$mount('#newComponent');
},

This works but the created component doesn't have a $store parameter, so on creation since the Financials component has a ...mapGetters("editMode")

and the template is

<template>
  <div>
    {{editMode}}
  </div>
</template>

On the call to the editMode computed property, it breaks. When I replace {{editMode}} with some static text, it runs fine. So, if what I'm doing in the first place isn't completely wrong, I'm just wondering how do I attach a store to the instance that I'm creating.


Solution

  • This is usually caused by not providing a parent component:

    var instance = new ComponentClass({
      parent: this,  // <-- Here
      propsData: {
        sizeLoc: this.defaultContainer,
        control: componentsItem.componentName,
      }
    });
    

    Assuming this is a component instance (which would be the case inside a component method).