1.首先先创建一个文件夹名字如:component 再在里面创建一个文件夹Tabs
2.在文件夹中右键选择component . 写入名字.
3.在page文件中的json中选择usingComponents 使用键值对的方式
例如----"usingComponents": {
"Tabs":"../../component/tabs/tabs"
}
4.在页面中可以直接使用Tabs当做标签使用.
自定义组件的使用
直接通过代码来解读.
···这个是直接创建的自定义组件---可以进行直接调用.
tab.xml
<view class="tabs" >
<view class="tabs_title" >
<!-- <view class="title_item active" >首页</view>
<view class="title_item" >原创</view>
<view class="title_item" >分类</view>
<view class="title_item" >关于</view> -->
<view
wx:for='{{Tabs}}'
wx:key='id'
class="title_item {{item.isActive? 'active':''}}"
bindtap = "handinput" //添加事件
data-index='{{index}}' //传递参数 其中参数数组中有两个参数 1.item 2.index 其中item表示该数组中的某一项 ,而index表示这是数组的索引.
>
{{item.name}}
</view>
</view>
<view class="tabs_content" >
<slot> </slot> //这个是个占位符.
</view>
</view>
····其中这个slot是占位符 ,
····data-index='{{index}}' 传递索引
这个是tab.js对里面的事件进行修改
// component/tabs/tabs.js
Component({
/**
* 组件的属性列表
*
* 父组件-----》子传递.
**/
properties: {
//接收数据的名称 必须要和页面上的名称一致
// aaa:{
// //type 表示接收的数据类型
// type:String,
// //表示默认值 ,若是没有就是这个值
// value:''
// },
Tabs:{
type:Array,
value:[]
}
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
* 1.页面的函数需要放到Data的同层级下!!!
* 2.组件中需要放到method中.!!!
*/
methods: {
handinput(e){
//可能是因为常量所以需要注意.
const {index} =e.currentTarget.dataset; //获取传递进来的参数.
this.triggerEvent("itemChange",{index}); //这个是将组件的参数传递到页面上.
//this.data获取data中的数组.两种意思相同.
// let {Tabs}=this.data;
// let Tabs=this.data.Tabs;
// Tabs.forEach((v,i) =>i===index?v.isActive=true:v.isActive=false);
// this.setData({
// Tabs:Tabs
// })
}
}
})
···父组件传参数给组件
···事件跟页面有些区别 只能放到 methods中
···this.triggerEvent("itemChange",{index}); //这个是将组件的参数传递到页面上. itemChange传递的名字 , index传递的数据.
··· Tabs.forEach((v,i) =>i===index?v.isActive=true:v.isActive=false);这个foreach循环会将数组中的数据在循环中改变.--->Tabs ,v是里面的数组 ,i是索引.
页面的调用自定义的组件
demo16.xml
1.父组件(页面) 向子组件 传递数据 通过 标签属性的方式
1.在子组件上进行接收.
-->
<Tabs Tabs="{{Tabs}}" binditemChange="handins">
<view wx:if="{{Tabs[0].isActive}}">0</view>
<view wx:if="{{Tabs[1].isActive}}">1</view>
<view wx:if="{{Tabs[2].isActive}}">2</view>
<view wx:if="{{Tabs[3].isActive}}">3</view>
</Tabs>
···其中这个组件中的内容就是组件的占位符.
···直接写组件的名字, 进行使用.
···Tabs="{{Tabs}}"--------------------------
1.父组件(页面) 向子组件 传递数据 通过 标签属性的方式,父组件(页面)
向子组件 传递数据 通过 标签属性的方式.
··· binditemChange="handins" 子组件向父组件传递内容.------------------------
demo.js
// pages/demo16/demo16.js
Page({
/**
* 页面的初始数据
*/
data: {
Tabs:[
{
id:0,
name:'首页',
isActive:true
},
{
id:1,
name:'原创',
isActive:false
},
{
id:2,
name:'分类',
isActive:false
},
{
id:3,
name:'关于',
isActive:false
}
]
},
handins(e){
const index=e.detail.index; //获取组件传递过来的参数
let Tabs=this.data.Tabs;
Tabs.forEach((v,i) =>i===index?v.isActive=true:v.isActive=false);
this.setData({
Tabs:Tabs
})
console.log(e);
}
})
···===是比较相等的.