vue——使用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" :posts="posts" :currentPost="currentPost"></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';
        },
    }

});

发布了44 篇原创文章 · 获赞 15 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/Sunshine0508/article/details/90039715