微信小程序-组件化
微信小程序-组件化
自定义组件
业务描述:代码中有多处需要引用同一段代码,需要把他封装成一个组件
流程
- 在根目录创建components用于存放通用组件
- 在创建组件文件夹
- 选择新建components 会自动生成4个文件
- json文件 会出现"component": true, 即组件创建成功
通用组件创建
section-info.wxml
<view><view>我是标题</view><view>我是内容</view>
</view>
index.wxml
主页面直接引用
<!--pages/05_learn_cpns/index.wxml-->
<!-- 自定义组件 -->
<section-info/>
<section-info/>
index.json
直接引用路径配置
{"usingComponents": {"section-info":"/components/section-info/section-info"}
}
也可在全局配置app.json中进行配置其好处就是配置后所有的page页面都可使用
"usingComponents": {"section-info":"/components/section-info/section-info"},
组件的样式
- 组件内不能使用id选择器,属性选择器,标签选择器
- 组建的class只对组件内有用
组件通信
类似于vue 的props
properties
往组件内传递数据
index.wxml
<!--pages/05_learn_cpns/index.wxml-->
<!-- 自定义组件 -->
<section-info title="hahah" content="zzzzz" />
<section-info title="hehehehe" content="aaaaa"/>
section-info.js
组件内
properties: {title:{type:String,value:"标题"},content:{type:String,value:"内容"}},/* 组件的初始数据*/data: {},
section-info.wxml
<view><view>{{title}}</view><view>{{content}}</view>
</view>
组件往外传递事件-自定义事件triggerEvent
section-info.wxml
组件bindtap绑定事件
<view><view bindtap="ontab">{{title}}</view><view>{{content}}</view>
</view>
section-info.js
组件写逻辑在methods中
methods: {ontab(){this.triggerEvent("titleclick","bbbb")}}
index.wxml
要传递的外部页面
<!--pages/05_learn_cpns/index.wxml-->
<!-- 自定义组件 -->
<section-info title="hahah" content="zzzzz" bind:titleclick="oninfo" />
<section-info title="hehehehe" content="aaaaa"/>
index.js
oninfo(event){// console.log("q111");console.log(event.detail);},
练习:
创建组件 navigation
navigation.wxml
<!--components/navigation/navigation.wxml-->
<!-- tab例子 -->
<view class="tab"><block wx:for="{{titles}}" wx:key="*this"><view class="item"bindtap="itemtap"data-index="{{index}}"class="item {{index === currentIndex ? 'active': ''}}">{{item}}</view></block>
</view>
navigation.wxss
.tab{display: flex;height: 40px;line-height: 40px;text-align: center;
}
.active{border-bottom: 3px solid #ff8189;padding: 5px;
}
.tab .item{flex: 1;
}
navigation.js
// components/navigation/navigation.js
Component({/* 组件的属性列表*/properties: {titles:{type:Array,value:[]}},/* 组件的初始数据*/data: {currentIndex:0},/* 组件的方法列表*/methods: {itemtap(event){//console.log(event.currentTarget.dataset);const currentIndex = event.currentTarget.dataset.indexthis.triggerEvent("titleclick",currentIndex)this.setData({currentIndex})}}
})
页面
导入组件
index.json
{"usingComponents": {"section-info":"/components/section-info/section-info","navigation":"/components/navigation/navigation"}
}
index.wxml
<!--pages/05_learn_cpns/index.wxml-->
<!-- 自定义组件 --><navigation titles='{{arr1}}' bind:titleclick="oninfo11" />
index.js
// pages/05_learn_cpns/index.js
Page({/* 页面的初始数据*/data: {arr1:["蔬菜","水果","青菜"]},oninfo11(event){console.log(event.detail);},})