在开发过程中,不断重复使用页面中的某一个模块,那么可以就这个模块封装成组件,在页面中直接以标签的形式调用组件。组件类似于页面,自定义组件都有自己的wxml,wxss等文件
创建自定义组件流程
- 在项目根目录下创建一个 components 文件夹,在文件夹下创建一个组件文件夹,在组件文件夹下创建四个对应的组件文件
注:每个组件 都有四个文件 component.wxml component.wxss component.json component.js
- component.wxml 组件的模板文件
- component.wxss 组件的样式文件
- component.json
{
"component": true, //告诉小程序 这是一个组件 如果当作组件使用 这个属性一定要设置为true
"usingComponents": {}//使用其他的组件
}
- component.js
Component({ //定义组件 记录了这个组件的所有逻辑任务
/**
* 组件的属性列表
*/
properties: {
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
}
})
运用自定义组件
很简单 类似vue 直接一标签形式 运用 <Nav></Nav>
***.json文件中引入
{
"usingComponents": {
"Nav" : "../components/Nav/Nav"
}
}
组件实例腾讯新闻导航
方式 1
<view class="tencentNews-nav">
<view class="{
{idx == 1 ? 'active' : ''}}" bindtap="click" data-index="1">推荐</view>
<view class="{
{idx == 2 ? 'active' : ''}}" bindtap="click" data-index="2">NBA</view>
<view class="{
{idx == 3 ? 'active' : ''}}" bindtap="click" data-index="3">足球</view>
<view class="{
{idx == 4 ? 'active' : ''}}" bindtap="click" data-index="4">综合体育</view>
<view class="{
{idx == 5 ? 'active' : ''}}" bindtap="click" data-index="5">CBA</view>
</view>
data: {
idx:1
},
methods: {
click:function(e){
console.log(e.target.dataset.index)
var key = e.target.dataset.index
this.setData({
idx:key
})
}
}
方式 2
<view class="tencentNews-nav">
<view
wx:for="{
{arr}}"
wx:key="id"
bindtap="click2"
data-index="{
{index}}"
class="{
{idx2 == index ? 'active' : ''}}"
>{
{item.title}}</view>
</view>
//js文件
data: {
idx2:0,
arr:[
{
id:0,
title:'推荐'
},
{
id:1,
title:'NBA'
},
{
id:2,
title:'足球'
},
{
id:3,
title:'综合体育'
},
{
id:4,
title:'CBA'
}
]
},
methods: {
click2:function(e){
console.log(e.target.dataset.index)
var key = e.target.dataset.index
this.setData({
idx2:key
})
}
}