父组件代码
<template>
<div class="page_content_container">
<div class="recommand_communities_container">
<community_card v-for="(community,index) in communities" v-bind:key="index" v-bind:community="community" v-on:onclick="onChosen" />
</div>
</div>
</template>
<script>
import community_card from '../community_card.vue';
export default {
components: { community_card},
name: "page_content",
data: function () {
return {
communities:[
{
id:'1'
name:'1-C',
intro:'1-C Test',
avatar:'/1-C-avatar.jpg'
selected:true
},
{
id:'2'
name:'2-C',
intro:'2-C Test',
avatar:'/2-C-avatar.jpg'
selected:false
},
{
id:'3'
name:'3-C',
intro:'3-C Test',
avatar:'/3-C-avatar.jpg'
selected:false
},
]
}
},
methods: {
onChosen:function(communityId){
for (let index = 0; index < this.communities.length; index++) {
const element = this.communities[index];
if(element.id == communityId ){
element.selected = true;
// element.name = 'DoTest'; 有这一行 子组件的 class 会变更 ,没有则不会变更
}else{
element.selected = false
}
}
}
},
};
</script>
<style scoped>
.page_content_container {
height: 800px;
width: 100%;
display:flex;
}
.recommand_communities_container {
height: 800px;
width: 240px;
margin: 0;
padding: 0;
display: inline-block;
}
.recommand_community_post_container {
border-radius: 15px;
height: 100%;
width: 100%;
margin: 0;
padding: 0;
border-left:1px solid rgba(0, 0, 0, 0.22);
display: inline;
}
</style>
子组件
<template>
<div class="community_card_container" v-bind:class="{'selected':community.selected}" v-on:click="onclick">
<div class="community_card_avatar_container">
<img :src="community.avatar" :title="community.name" />
</div>
<div class="community_card_base_info_container">
<div>{{ community.name }}</div>
<div>{{ community.intro }}</div>
</div>
</div>
</template>
<script>
export default {
name: "community_card",
data: function () {
return {
}
},
methods: {
onclick: function () {
this.$emit('onclick',this.community.id)
},
},
props:['community']
};
</script>
<style scoped>
.community_card_container {
height: 76px;
width: 236px;
border: lightslategray 2px solid;
display: flex;
border-radius: 10px;
}
.selected{
background-color:lightskyblue ;
}
.community_card_container .community_card_avatar_container {
height: 76px;
width: 76px;
display: inline;
text-align: center;
}
.community_card_container .community_card_base_info_container {
width: 136px;
border-left:rgb(177, 171, 204) 2px solid;
}
.community_card_container .community_card_avatar_container img {
width: auto;
height: auto;
max-width: 100%;
max-height: 100%;
}
.community_card_container .community_card_base_info_container div {
height: 38px;
width: 136px;
line-height: 38px;
text-align:center;
overflow:hidden;
}
</style>
请教原因和怎么解决
这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。
V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。
V2EX is a community of developers, designers and creative people.