开始
–创建组件
创建组件文件夹
components
–>News–>新建Component
–分析组件结构
- wxml:存放组件结构
- wxss存放组件样式
- json:用来决定使用的组件
{
"usingComponents": {
}
}
- js:
/**
* 组件的属性列表
*/
properties: {
},
/**
* 组件的初始数据
*/
data:{
},
/**
* 组件的方法列表
*/
methods: {
}
实现组件的使用
页面wxml
<view class="news">
<view class="news_title">
<view class="new_item {
{item.isSel ? 'active' : ''}}" wx:for="{
{titles}}" wx:key="{
{item.id}}" data-id="{
{item.id}}"
bindtap="handletitle">{
{item.name}}</view>
</view>
<view class="news_context">新闻内容</view>
</view>
样式wxss
/* components/News/News.wxss */
.news_title{
display: flex;
padding: 10rpx;
}
.new_item{
flex: 1;
display: flex;
justify-content: center;
}
.active{
color: greenyellow;
border-bottom: 5rpx red solid;
}
js
父向子传参–>
properties中定义参名:类型
// components/News/News.js
Component({
/**
* 组件的属性列表
*/
properties: {
titles:{
type:Array,
value:[]
}
},
/**
* 组件的初始数据
*/
data: {
},
/**
* 组件的方法列表
*/
methods: {
handletitle(e){
console.log(this.data.titles);
//子传父(参数传id)
this.triggerEvent('itemChange',e.target.dataset.id);
//下方代码只能修改自身data数据...
/*
let ok =this.data.titles.filter(item=>{
if(item.id==e.target.dataset.id){
item.isSel=true;
}else{
item.isSel=false;
}
return item;
})
this.setData({
titles:ok
});*/
}
}
})
需要用该组件的项目
wxml
使用
参数名=值
传参
<!--pages/day4/day4.wxml-->
<News titles="{
{titles}}" binditemChange="xgstate"></News>
js
Page({
/**
* 页面的初始数据
*/
data: {
titles:[
{
id:1,name:'首页',isSel:true},
{
id:2,name:'热点',isSel:false},
{
id:3,name:'疫情分析',isSel:false},
{
id:4,name:'新闻',isSel:false}
]
},
xgstate:function(id) {
let ok =this.data.titles.filter(item=>{
if(item.id==id.detail){
item.isSel=true;
}else{
item.isSel=false;
}
return item;
})
this.setData({
titles:ok
});
},
})
json
使用
News
组件
{
"usingComponents": {
"News":"../../components/News/News"
}
}
效果图
成功实现自定义组件的使用,觉得文章对你有帮助就点个赞支持以下叭~