【问题标题】:Dynamically add a child component in Vue JS在 Vue JS 中动态添加子组件
【发布时间】:2018-07-02 00:42:33
【问题描述】:

我需要在 Vue JSLaravel 添加子 vue 组件方面的帮助。

我有一个名为“wrapper”的父组件和一些名为"show-1""show-2""show-3" ...等的子组件。

父组件:

<template>
    <div class="card border-light">
        <div class="card-header">
            <h5 class="title">{{ title }}</h5>
        </div>
        <div class="card-body">
            <component
                is="view"
            ></component >
        </div>
        <div class="card-footer"></div>
    </div>
</template>

<script>
export default {
    props : ['title'],
    data() {
        return {
            view : ''
        }
    }
}
</script>

像“show-1”这样的示例子组件:

<template>
    <div> show-1 </div>
</template>

以下代码在刀片中用于呈现具有动态子组件名称的包装器组件:

<wrapper
title="Example"
view="show-1"
></wrapper>

此代码不起作用,但如果我更改父视图数据“show-1”而不是空,它会起作用。为什么?

当我改变视图道具时,子 vue 组件也应该改变。我怎么能这样做?

我想动态地将视图属性传递给父组件。

【问题讨论】:

    标签: javascript laravel vuejs2 laravel-5.4 vue-component


    【解决方案1】:

    您可以使用:is 属性。你可以在这里读更多关于它的内容: https://vuejs.org/v2/guide/components.html#Dynamic-Components

    您可以使用相同的挂载点并在它们之间动态切换 使用保留元素的多个组件和 动态绑定到它的 is 属性....

    <template>
        <div class="card border-light">
            <div class="card-header">
                <h5 class="title">{{ title }}</h5>
            </div>
            <div class="card-body">
                <!-- make sure to use : -->
                <component v-if="view" :is="view"></component >
            </div>
            <div class="card-footer"></div>
        </div>
    </template>
    
    <script>
    export default {
        props : ['title'],
        data() {
            return {
                view : ''
            }
        }
    }
    </script>
    

    【讨论】:

    • 我应该为包装器组件编写刀片模板并发送子 vue 组件以完全渲染。 (我需要 最后一个带有所有道具和属性的文本)
    【解决方案2】:

    @Eduardo 有正确的答案。要添加它,请将您的组件导入父组件并通过数据属性在它们之间切换:

    ...
    <component :is="current"></component >
    ...
    
    data: {
      current: 'show1'
    },
    components: {
      show1: Show1Component,
      show2: Show2Component,
      show3: Show3Component
    }
    

    关键是使用动态组件的名称来绑定组件。

    https://vuejs.org/v2/guide/components.html#Dynamic-Components

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-13
      • 1970-01-01
      • 2018-10-29
      • 2015-09-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多