使用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,怎么办呢?
不知道你是不是在子组件currentTabComponent中获取不到这俩个属性?
如果是子组件中,那么可以这么写,通过在子组件中得注册
props: ['posts', 'currentPost']
属性配置