微信小程序 自定义组件
原创
©著作权归作者所有:来自51CTO博客作者咸咸瑜瑜的原创作品,请联系作者获取转载授权,否则将追究法律责任
一般创建一个 components 的文件夹来管理,一个自定义组件由 json
wxml
wxss
js
4个文件组成。
首先需要在 json
文件中进行自定义组件声明(将 component
字段设为 true
可将这一组文件设为自定义组件):【如果是按照下面的方式常见 是自动生成的】
注意: 这里的 compoments 打错了 应该是: component
然后微信小程序会自动创建好那四个页面 ,和普通页面的没什么区别,但是js文件中用的不是page() 而是 compontent :


// compoments/tabs/tabs.js
Component({
/**
* 组件的属性列表
*/
properties: {
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
}
})
tabs.js
tabs.js:

我们做一个小小的导航栏吧:
组件tabs:
tabs.wxml
<view class="tabs">
<view class="tabs_title">
<!--
其中:data-index 是一个传参(JS基础)
-->
<view wx:for="{{tabs}}" class="tabs_item {{item.isActive === true ? 'active' :''}}" wx:key="id" bindtap="active" data-index="{{index}}" >{{item.title}}</view>
</view>
<view class="tabs_content">内容</view>
</view>


{
"component": true,
"usingComponents": {}
}
tabs.json


Component({
/**
* 组件的属性列表
*/
properties: {
},
/**
* 组件的初始数据
*/
data: {
tabs:[
{id:0,title:"首页",isActive:true},
{id:1,title:"社区",isActive:false},
{id:2,title:"交易",isActive:false},
{id:3,title:"个人",isActive:false},
]
},
/**
* 组件的方法列表
*/
methods: {
active(e){
const index = e.currentTarget.dataset.index; //获取点击下标
const tabs = [].concat(this.data.tabs); //复制data中的tabs。
tabs.forEach(v => {index == v.id?v.isActive = true : v.isActive = false});
console.log(tabs);
this.setData({
tabs
})
console.log(this.data);
}
}
})
tabs.js


.tabs_title{
display: flex;
padding: 10rpx;
}
.tabs_item{
flex:1;
text-align: center;
}
.active{
border-bottom: 10rpx solid red;
}
tabs.wxss
使用组件 index页面:


{
"usingComponents": {
"tabs":"../../components/tabs/tabs"
}
}
index.json
效果图:

作者:咸瑜