
以上效果,由四个ets文件实现,分别是容器页面。首页,购物车,我的。
页面里的数据,我是用json-server进行模拟的数据。
一、容器页面
使用组件Tabs和Tabcontent结合。
import Home from "./Home";
import ShoppingCar from "./ShoppingCar";
import My from "./My";
@Entry
@Component
struct TabsExample {
// 定义变量,表示当前选中的下标
@State currentIndex:number = 0;
@State arr:Array<Object> =[
{
icon:"/imgs/home.png",
selectedIcon:"/imgs/home2.png",
text:"首页"
},
{
icon:"/imgs/gouwuche.png",
selectedIcon:"/imgs/gouwuche2.png",
text:"购物车"
},
{
icon:"/imgs/wode.png",
selectedIcon:"/imgs/wode2.png",
text:"我的"
}
]
build() {
Column() {
Tabs({ barPosition: BarPosition.End }) {
ForEach(this.arr,(item,idx)=>{
TabContent() {
if(this.currentIndex==0){
Home()
}else if(this.currentIndex==1){
ShoppingCar()
}else{
My()
}
}.tabBar({
icon: (this.currentIndex==idx)?item.selectedIcon:item.icon,
text:item.text
})
})
}
.width(360)
.height("100%")
.onChange((idx)=>{
this.currentIndex = idx;
})
}.width('100%')
}
}
二、首页
import http from '@ohos.net.http';
import router from '@ohos.router';
interface IBook{
id:string,
name:string,
author:string,
publish:string,
img:string
}
@Entry
@Component
// 对外开放
export default struct Home {
@State books:Array<IBook> = [];
@State imgs: Array<string> = [];
scroller: Scroller = new Scroller()
// 创建http的请求对象
httpRequest = http.createHttp();
// 获取轮播图数据
getBanners(){
this.httpRequest.request("http://localhost:3000/bannerImgs",(err,data)=>{
if(!err){
this.imgs = JSON.parse(data.result as string);
this.initScroll();
}
})
}
// 获取书籍信息
getBooks(){
//发送请求
this.httpRequest.request("http://localhost:3000/books",(err,data)=>{
if(!err){
// console.log("data",data)
// data对象的result属性是数据
// console.log("data.result",data.result)
// JSON.parse():把字符串转成json对象。
this.books = JSON.parse(data.result as string);
}
})
}
// aboutToAppear():这个生命周期钩子函数的调用时机:当本页面(组件)加载时,
aboutToAppear(){
this.getBooks();
this.getBanners();
}
// 自行实现轮播图功能:
initScroll(){
let index = 0;
let maxIndex = this.imgs.length-1;
setInterval(()=>{
index++;
if(index>maxIndex){
index = 0;
}
this.scroller.scrollTo({
xOffset:index*400,
yOffset:0,
animation:{
duration:1000,
curve:Curve.Linear
}
})
},2000)
}
build() {
// 最外层使用弹性盒布局,纵向分为三部分:搜索框,滚动容器,底部。
Flex({ direction: FlexDirection.Column, justifyContent: FlexAlign.SpaceBetween }) {
// 1、搜索框
Search({ placeholder: '请输入您要搜索的内容', icon: "imgs/search01.png" })
.searchButton('搜索')
.textAlign(TextAlign.Center)
.width("100%")
.height(60)
.backgroundColor('#F5F5F5')
.placeholderColor(Color.Grey)
.placeholderFont({ size: 20, weight: 400 })
.textFont({ size: 30, weight: 400 })
.onSubmit(()=>{
console.log("onSubmit")
router.pushUrl({
url:"pages/SearchPage"
})
})
Scroll() {
Column() {
// 1)、轮播图
List({scroller:this.scroller}){
For

最低0.47元/天 解锁文章
3780

被折叠的 条评论
为什么被折叠?



