【问题标题】:Dynamic props in component tag with Vue tab带有 Vue 选项卡的组件标签中的动态道具
【发布时间】:2021-02-13 11:54:18
【问题描述】:

我有一个我自己无法解决的问题。

我想用 Laravel 和 Vue (SPA) 创建一个简单的新闻门户应用程序

我有一个 Home / Index 组件,其中包含许多选项卡(Vue 选项卡)

在每个标签中,我想根据它们的类别显示不同的新闻 比如健康、科技、游戏等

所以在我的 App.vue 中

<template>
    <div>
        <button type="button"
            v-for="tab in tabs" :key="tab"
            @click="changeTab(tab)"
        >{{ tab }}</button>
    </div>
    <div>
        <component :is="currentTab"></component>
    </div>
</template>

<script>
    import Health from '...'
    import Technology from '...'
    import Gaming from '...'
    import ...
    import ...

    export default {
        components: {
            Health,
            Technology,
            Gaming,
            ...
        },
        data() {
            return {
                currentTab: 'Health', // Starting point, (when user visit the index)
                tabs: [
                    'Health',
                    'Technology',
                    'Gaming',
                    ....
                ],
                health: [
                    // object, title, image, etc, source
                ],
                technology: [
                    // object, title, image, etc, source
                ],
                ...
            }
        },
        methods: {
            changeTab(val) {
                this.currentTab = val
            }
        }
    }
</script>

如何使用 props(或任何其他方式)将数据从这个组件传递到健康、技术、游戏组件?

<component :is="currentTab"></component>
// Idk how to pass them within this component tag

【问题讨论】:

    标签: vuejs2 vue-component


    【解决方案1】:

    在不知道这些组件期望它们的 props 采用什么结构的情况下,我建议采用这样的方法:

        <component
            :is="currentTab"
            v-bind="currentProps"
        />
    
        ...
    
        computed: {
            currentProps() {
                return this[this.currentTab.toLowerCase()];
            }
        }
    

    【讨论】:

    • 抱歉回复晚了,你的回答和我预期的一样,我忘了说每个子组件都使用了 props: data
    • 所以在我的子组件中会是这样的:props: ['data']
    猜你喜欢
    • 2014-09-09
    • 2015-06-18
    • 1970-01-01
    • 2020-10-24
    • 2016-12-28
    • 2018-04-20
    • 2016-07-19
    相关资源
    最近更新 更多