【问题标题】:How can I use a child component in the parent component?如何在父组件中使用子组件?
【发布时间】:2020-12-28 08:18:06
【问题描述】:

我有这种情况:

父组件(Parent.vue):

<template>
........
</template>
    
<script>
export default {
name: 'Parent'
...........
</script

子组件(Child.vue):

<template>
........
</template>
    
<script>
export default {
name: 'Child'
...........
</script

为了在父组件的模板中使用子组件(子组件模板)需要做什么?步骤是什么?

【问题讨论】:

  • 您将从Vue guide: Component Basic 学习如何使用。例如:在Parent.vue 中,使用&lt;template&gt;&lt;child&gt;&lt;/child&gt;&lt;/template&gt;
  • 子组件需要先注册吗?如果有,应该怎么做?

标签: vue.js vue-component


【解决方案1】:

您可以将 Child 作为本地组件调用 as stated in the documentation

components 将组件声明为对象。

父.vue:

<template>
    <child></child>
</template>

<script>
//Import the Child component to the parent
import Child from "@/path/to/Child.vue";

export default {
    name: 'Parent',//Declare the components object 
    components: {
        //Declare your components here
        Child //This is the Child component
    }
...........
</script>

【讨论】:

  • 您能否向我解释一下插入的代码行以及它们应该按什么顺序插入?谢谢
  • 我插入了 import: import Child from "@/path/to/Child.vue"; 以便在父组件中调用子组件
  • 并在Parentname之后插入components: {Child},因为这就是Parent知道它必须使用Child组件的方式,您可以声明更多组件,如components: {Child1, Child2, Child3}
  • 欲了解更多信息,请查看docs,它有很多示例。
  • 谢谢,是在父组件模板中插入标签,之后的最后一步:1)import Child from "@/path/to/Child.vue" ;和 2) 组件:{Child} ??对吗?
猜你喜欢
  • 2019-08-26
  • 2020-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-04-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多