使用v-bind:is 切换组件的时候怎么传数据?

使用v-bind:is 切换组件的时候,这个时候再怎么绑定属性来传递数据呀?

<div id="exp">
    <tab-btn v-for="tab in tabs" :key="tab.id" :tab="tab">
    </tab-btn>
    <keep-alive>
        <component v-bind:is="currentTabComponent"></component>
    </keep-alive>
</div>

通过改变 currentTabComponent 切换组件

Vue.component('posts-component', {
    props: ['posts', 'currentPost'],
    template: `
        <div @post-change="currentPost = $event" :posts="posts" :currentPost="currentPost">
            <ul>
                <li v-for="post in posts" @click="$emit('post-change', post)">
                {{ post.title }}
                </li>
            </ul>
            <div>
                <p v-if="!currentPost">Click on a blog to view it.</p>
                <div v-else>
                    <h1>{{ currentPost.title }}</h1>
                    <p>{{ currentPost.content }}</p>
                </div>
            </div>
        </div>
        
    `
});

let app = new Vue({
    el: '#exp',
    data: {
        tabs: [
            { name: 'Posts', id: 1 },
            { name: 'Archive', id: 2 }
        ],
        chose: 'Posts',
        posts: [
            { title: 'Cat Ipsum', content: 'fuck' },
            { title: 'Hipster Ipsum', content: 'fuck2' },
            { title: 'Cupcake Ipsum', content: 'fuck3' }
        ],
        currentPost: null,

    },
    computed: {
        currentTabComponent() {
            return this.chose.toLowerCase() + '-component';
        },
    }

});

可是这时候没法访问到 data里的 posts 和 currentPost,这两个都是 undefined,怎么办呢?

阅读 4.2k
1 个回答

不知道你是不是在子组件currentTabComponent中获取不到这俩个属性?
如果是子组件中,那么可以这么写,通过在子组件中得注册 props: ['posts', 'currentPost'] 属性配置

<component v-bind:is="currentTabComponent" :posts="posts" :currentPost="currentPost"></component>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题