如何解决同一个页面,for循环同一组件,组件内部的data互相影响?
我写了一个自定义组件,然后在A页面for循环该组件,发现子组件内,data中的变量共享了,我在第一个子组件内部写了一个点击事件,改变第一个子组件(他自己)的data变量,发现第二三四五六个组件中的data变量都同时修改了,想问下有无解决办法。 子组件(所有子组件的morePetsStatus会被统一修改): <style lang='less'>
...
</style>
<template>
<view class='collection_item_view'>
<view class='collection_item_inner_view display_flex_row'>
<view class='collection_item_pet_icon'></view>
<view class='collection_item_pet_info_view'>
<view class='collection_item_pet_name_view display_flex_row_center_space_between'>
<text class='collection_item_pet_name_content'>收藏的商品</text>
<text class='collection_item_pet_introduction'>用于打标</text>
</view>
<view class='collection_item_pet_tags_view display_flex_row_center_flex_start'>
<view class='collection_item_pet_tag_content'>标签1</view>
<view class='collection_item_pet_tag_spline' />
<view class='collection_item_pet_tag_content'>标签2</view>
</view>
<view class='collection_item_pet_price_info_view display_flex_row_flex_end_space_between'>
<view class='collection_item_pet_price_view display_flex_row_flex_end_flex_start'>
<view class='collection_item_pet_price_symbol'>¥</view>
<view class='collection_item_pet_price_content'>10086</view>
</view>
<view @tap='modifyMorePetsStatus' class='collection_item_pet_more_view display_flex_row_center_flex_end'>
<view class='collection_item_pet_more_content'>找伙伴</view>
<image
class="collection_item_pet_more_right_arrow_icon {{ morePetsStatus ? 'collection_item_pet_more_right_arrow_icon_up' : '' }}"
src='/images/right_arrow.png' />
</view>
</view>
</view>
</view>
</view>
</template>
<script>
import wepy from 'wepy'
export default class CollectionItem extends wepy.component {
props = {}
data = {
morePetsStatus: false
}
components = {}
methods = {
modifyMorePetsStatus() {
this.morePetsStatus = !this.morePetsStatus
}
}
}
父组件:
<repeat for='{{collectionList}}' key='index' index='index' item='item'>
<CollectionItem />
</repeat>
data = {
collectionList: [
{ key: 'collection_01' },
{ key: 'collection_02' },
{ key: 'collection_03' },
{ key: 'collection_04' },
{ key: 'collection_05' }
],
}
我已有两个解决办法,但是不太想用: 1、分别引入组件,并注册不同的名字,但是此方案仅可实现写死固定个数的组件,无法做到动态for循环(个数可变)。 components = {
components1,
components2,
components3
}
2、子组件内部的值由父组件控制,也可解决,但这会导致代码非常冗余,且失去了组件化的意义。 截图如下,我只改变了第一个组件中data的num值,加了一个1,第一个组件确实变成了2,但是下面的组件全部变成了2。 [图片][图片]