首页 > 解决方案 > 带有 Vue 选项卡的组件标签中的动态道具

问题描述

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

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

我有一个带有许多选项卡(Vue 选项卡)的 Home / Index 组件

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

所以在我的 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>

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

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

标签: vuejs2vue-component

解决方案


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

    <component
        :is="currentTab"
        v-bind="currentProps"
    />

    ...

    computed: {
        currentProps() {
            return this[this.currentTab.toLowerCase()];
        }
    }

推荐阅读