【问题标题】:How to import a component as prop from another component?如何从另一个组件导入一个组件作为道具?
【发布时间】:2020-10-13 12:10:41
【问题描述】:

可以从另一个组件导入一个组件作为道具吗?

例如:

Q-对话框

 <template>
  <q-dialog>       
    <q-layout>
        <q-page-container>
        
          <myCustomComponent />

      </q-page-container>
    </q-layout>
  </q-dialog>
</template>

<script>    
//Edited:This works, but I want to register dynamically from props
//import myCustomComponent from "components/MyCustomComponent.vue";

import myCustomComponent from this.myComponent;
    
export default {  
  props: ["myComponent"],
  components: { myCustomComponent }
}

另一个组件:

this.$q.dialog({
    component: CustomComponent, //dialog
    myComponent: 'components/MyCustomComponent.vue'
})

已编辑,为了更好地阐明我在这种情况下要实现的目标:

我的对话框是一个 abstract 组件,其中可以呈现无限数量的不同 myCustomComponent。

为此,我需要每个组件(导入)的注册在 q-dialog 中完成。

要考虑的解决方案是在加载 q-dialog 以进行渲染的文件中注册每个组件(不同于 q-dialog,在我的情况下是 另一个组件 文件),然后将该路径从导入的文件传递到 q-dialog,可能作为道具。

这可能吗?

已编辑解决方案:

父组件

<script>    
 import registeredComponent from "components/MyCustomComponent.vue";

 export default {
    data() {
      return {        
          myComponent: registeredComponent
      }
    }
        
  methods: {
      btnClickShowDialog(){
          this.$q.dialog({
              component: dialogComponent,
              //pass registered component as prop to dialog
              myCustomComponent: this.myComponent 
          })
      }   
  }
</script>

Q-对话框

<template>
  <q-dialog>       
    <q-layout>
        <q-page-container>
        
          <component :is="myCustomComponent" />

      </q-page-container>
    </q-layout>
  </q-dialog>
</template>

<script>        
    export default {  
      props: ["myCustomComponent"]
    }
</script>

【问题讨论】:

标签: vue.js quasar


【解决方案1】:

在您的 q-dialog 组件中,您可以使用 component 标签动态呈现传入的组件道具。看到这个stackblitz

// q-dialog html
<component :is="myComponent" />

在您的父组件中,您需要导入所需的组件,将其分配给数据属性并传入

// parent component js
import SomeComponent from './SomeComponent.vue'

data () {
    return {
        passedInComponent: SomeComponent
    }

}
// parent component html
<q-dialog :my-component="passedInComponent" />

【讨论】:

  • 谢谢 LLai。在我看来,您的解决方案非常适合这种情况。尽管进行了多次尝试,但我找不到基于从父方法使用 this.$q.dialog ({}) 呈现 q-dialog 并将 q-dialog 子组件作为道具传递的解决方案。一个可能的解决方案是全局注册组件,但我不想遵循该解决方案。再次感谢。
  • 我用适合我的情况的解决方案编辑了我的问题。感谢您提供了很大帮助的建议。
  • @josei 很高兴我能帮上忙!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-02
  • 2021-07-03
  • 2019-02-26
相关资源
最近更新 更多