目前自学微信小程序,为了加深印象,纯属记录一下,大家有更多的解决方案希望不吝赐教,万分感谢
需求:
父组件给子组件传入数据,子组件循环渲染出来,点击将index传递给父组件,父组件改变tabs数据
// 父组件list数据
tabs: [{
id: 0,
value: "综合",
isActive: true
},
{
id: 1,
value: "销量",
isActive: false
},
{
id: 2,
value: "价格",
isActive: false
}
],
父组件传递tabs给子组件
//父组件
<tabs tabs="{{tabs}}"></tabs>
子组件接收
//tabs.js文件
Component({
/**
* 组件的属性列表
*/
properties: {
tabs:Array,
},
})
子组件循环处理父组件传过来的数据
<view class="">
<view class="top">
<view
class="top_list {{item.isActive?'active':''}}"
wx:for="{{tabs}}"
wx:key="id"
bindtap="listIndex"
data-index="{{index}}">
{{item.value}}
</view>
</view>
</view>
子组件点击不同的循环项,将下标传递给父组件
Component({
properties: {
tabs:Array,
},
methods: {
listIndex(e){
const {index} = e.currentTarget.dataset
//利用this.triggerEvent将index传递给父组件,并且执行父组件中listIndex方法
this.triggerEvent("listIndex",{index})
}
}
})
父组件执行listIndex方法
//需要在自定义方法前面加上'bind'
<tabs tabs="{{tabs}}" bindlistIndex="listIndex"></tabs>
父组件JS文件
import {
request
} from '../../request/index.js'
Page({
data: {
// 父组件list数据
tabs: [{
id: 0,
value: "综合",
isActive: true
},
{
id: 1,
value: "销量",
isActive: false
},
{
id: 2,
value: "价格",
isActive: false
}
],
},
// 获取子组件传来的下标修改数据
listIndex(e) {
const {index} = e.detail
const tabs = JSON.parse(JSON.stringify(this.data.tabs))
tabs.forEach((v,i)=>i===index?v.isActive=true:v.isActive=false)
this.setData({
tabs
})
}
})
最后效果