Creating component programmatically in Nuxt.js
Asked Answered
P

2

9

I'm trying to create a nuxt.js component programmatically. I tried the approach below which works in Vue. But it doesn't seem to work in nuxt.js because it instantiates the component on the Vue object. So it can not access its parent's data.

  var ComponentClass = Vue.extend(component_to_use);
  var instance = new ComponentClass();
  instance.$mount(); // pass nothing
  this.$refs.container.appendChild(instance.$el);

I cant find I way to do this correctly in Nuxt.js. Does anybody know how to do this? Note: I know I can pass the data as a prop but this is inefficient.

Phrenic answered 10/4, 2021 at 6:36 Comment(0)
S
0

Try this method ( with tirgger and refs )

first create your public component with name myCompnoent

//myComponent
<template></template>
<script>
export default(){
   method:{
     myMethod(){
       console.log('event')
     },
     eventMethod(val){
       console.log(val)
     }
   }
   props:['trigger'],
   watch:{
     trigger(){
        this.myMethod();
     }
   }
}
</script>

next create one js file and use myCompnoent with this method

import Vue from "vue";
import myComponent from "myComponent";
Vue.component("componentName", myComponent);

so now we are wanna use myComponent

<componentName $ref="compName"
               :trigger="trigger"></componentName>
<button @click="firstMethod()">first method</button>
<button @click="secondMethod()">second method</button>
<script>
 export default(){
   data(){
    trigger:0
   }    
 },
 methods:{
   firstMethod(){
     this.$refs.compName.eventMethod('text')
   },
   secondMethod(){
     this.trigger++
   }
 }
</script>
Secretive answered 10/4, 2021 at 6:36 Comment(0)
W
0

Maybe a little late, but I had similar problem in my Nuxt 2 App. In the end, I found out that passing an explicit parent to constructor options, should solve this problem.

export async function manualComponent(component, options = {}) {
    // can be removed if you want it to work on the server side
    if (process.server) return

    let rootInstance = getRootInstance()

    if (!rootInstance) await nextTick() // requires composition api

    rootInstance = getRootInstance()

    const ComponentClass = Vue.extend(component)
    const instance = new ComponentClass({ ...options, parent: rootInstance })

    instance.$mount()
    // we appending it in the same DOM tree, but we could add it deeper in any other place
    rootInstance.$el.appendChild(instance.$el)

    return instance
}

function getRootInstance() {
    // we need to retrieve a root Vue app instance
    return document.getElementById('__nuxt').__vue__
}

You can also pass other component's instance to it, or use getCurrentInstance and try to resolve it automatically with composable

Weatherglass answered 8/8, 2023 at 13:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.