鸿蒙next 电商实战项目 来了

1,083 阅读3分钟

前言:

最新在学习鸿蒙next 开发 就写了一个demo 今天就分享给大家一下

效果图

image.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

image.png

具体实现

  • 添加网络权限

image.png

启动本地服务

拿到项目里面的bosstabservice 配置好数据库 启动服务

image.png

客户端实现

  • 1 底部导航器实现
import choice from '../view/ChoicePage'
import HomePage from '../view/HomePage'
import MyPage from '../view/MyPage'
import Shoppingcar from '../view/Shoppingcar'
import prompt from '@ohos.promptAction';
import common from '@ohos.app.ability.common';





interface TabInterface{
  id:number
  title:string
  icon:ResourceStr
  selectIcon:ResourceStr
}
@Entry
@Component
struct Main {
  private backTime :number=0;
  showtoast(msg:string){
    prompt.showToast({
      message:msg
    })
  }
  //@State message: string = '首页';
  //Tabs组件的控制器,用于控制Tabs组件进行页签切换。
  private controller:TabsController = new TabsController();
  @State
  tablist:TabInterface [] = [{
    id:0,
    title:'首页',
    icon:$r('app.media.shouyeblue'),
    selectIcon:$r('app.media.shouyeblack')
    },
    {
      id:1,
      title:'推荐',
      icon:$r('app.media.tuijianblue'),
      selectIcon:$r('app.media.tuijianblack')
    },
    {
      id:2,
      title:'购物车',
      icon:$r('app.media.shoppingblue'),
      selectIcon:$r('app.media.shoppingblack')
    },
    {
      id:3,
      title:'我的',
      icon:$r('app.media.myblue'),
      selectIcon:$r('app.media.myblack')
    },
  ]
  //存储选择的下标
  @State currentIndex:number = 0
  @Builder
  tabBarItem(item:TabInterface){
    Column(){
      Image(item.id === this.currentIndex ? item.icon:item.selectIcon)
        .width(25)
        .height(25)
        .margin({top:5})

      Text(item.title)
        .fontSize(20)
        .fontColor(item.id === this.currentIndex ? '#1296db':'#2c2c2c')
        .margin({top:5})
    }.height(60)
    .width('100%')
  }

  build() {
    Row() {
      Tabs({index:$$this.currentIndex,controller:this.controller}){
        ForEach(this.tablist,(item:TabInterface)=>{
          TabContent(){
            if (0 ===this.tablist[this.currentIndex].id){
              HomePage()
            } else if(1 === this.tablist[this.currentIndex].id){
              choice()
            } else if(2 === this.tablist[this.currentIndex].id){
              Shoppingcar()
            } else  if(3=== this.tablist[this.currentIndex].id){
              MyPage()
            }
          }.tabBar(this.tabBarItem(item))
        })
      }.barPosition(BarPosition.End)
    }
    .height('100%')
  }

  onBackPress(): boolean | void {
    let nowtime=Date.now();
    if(nowtime-this.backTime<1000){
      const  mContext=getContext(this) as common.UIAbilityContext;
      mContext.terminateSelf()
    }else{
      this.backTime=nowtime;
      this.showtoast("再按一次将退出当前应用")
    }
    return true;
  }
}

网络请求工具类

import http from '@ohos.net.http';
import Logger from './Logger'
import Constants, { ContentType } from '../common/Constants';
import { connection } from '@kit.NetworkKit';
import { healthStore } from '@kit.HealthServiceKit';


export  function   httpRequestGet(url:string,params?:string){
  return httpRequest(url,http.RequestMethod.GET,params);
}
export  function   httpRequestPost(url:string,params?:string){

  return httpRequest(url,http.RequestMethod.POST,params);
}
function  httpRequest(url:string ,method:http.RequestMethod,params?:string):Promise<string>{
   let  httpRequest=http.createHttp();
   let responseResult=httpRequest.request(url,{
     method:method,
     readTimeout:Constants.HTTP_READ_TIMEOUT, //读取超时时间可选  默认 600000
     header:{
       'Content-Type':ContentType.JSON
     },
     connectTimeout:Constants.HTTP_READ_TIMEOUT, //连接超时时间  可选,默认为60000ms
     extraData:params // 请求参数

   });
   let getjson:string='';
   return responseResult.then((value:http.HttpResponse)=>{
      Logger.error("请求状态-- >"+value.responseCode);
      if(value.responseCode===200){
        Logger.error("请求成功");
        let result= `${value.result}`;
        Logger.error("请求返回数据",JSON.parse(result));
        getjson=result;
      }else{
        getjson='';
      }
     return getjson;
   }).catch(()=>{
      //httpRequest.off("headerReceive");
     httpRequest.destroy();
     return '';
   });
}

日志工具类



import hilog from '@ohos.hilog';

class Logger {
  private domain: number;
  private prefix: string;
  private format: string = '%{public}s, %{public}s';

  /**
   * constructor.
   *
   * @param Prefix Identifies the log tag.
   * @param domain Domain Indicates the service domain, which is a hexadecimal integer ranging from 0x0 to 0xFFFFF.
   */
  constructor(prefix: string = 'MyApp', domain: number = 0xFF00) {
    this.prefix = prefix;
    this.domain = domain;
  }

  debug(...args: string[]): void {
    hilog.debug(this.domain, this.prefix, this.format, args);
  }

  info(...args: string[]): void {
    hilog.info(this.domain, this.prefix, this.format, args);
  }

  warn(...args: string[]): void {
    hilog.warn(this.domain, this.prefix, this.format, args);
  }

  error(...args: string[]): void {
    hilog.error(this.domain, this.prefix, this.format, args);
  }
}

export default new Logger('HTTPS', 0xFF00)

其他的页面我这边就不展开讲了更多的可以关注我的课程 各位同学如果想学习更多的知识可以关注我的B站课程

最后总结:

鸿蒙的 ark ui 非常类似flutter 这种声明式ui 所有的布局都是代码编写的和传统的布局和逻辑分开有些区别 刚开始上手的时候可能不适应,慢慢就习惯了 还有一点 代码嵌套 这个其实可以把每个组件抽离出来就可以解决鸿蒙的ark ui 网络部分也是类似前端的http 请求 解析json和前端也比较像 也有面向对象编程的思想, 对前端和移动端同学来说也比较好理解和学习。 今天的文章就讲到这里有兴趣的 关注我B站教程 了解更多鸿蒙开发的知识 可以关注坚果派公众号 。 谢谢

课程地址

www.bilibili.com/cheese/play…

项目内容:

  • 1 常用布局组件的学习
  • 2 网络请求工具类封装
  • 3 arkui 生命周期启动流程
  • 4 日志工具类的封装
  • 5 自定义组合组件的封装
  • 6 路由导航跳转的使用
  • 7 本地地数据的缓存 以及缓存工具类的封装
  • 8 欢迎页面的实现
  • 9 登录案例和自动登录效果实现
  • 10 请求网络数据分页上拉加载 下拉刷新的实现
  • 11 list数据懒加载实现
  • 12 webview组件的使用

如果使用更多好用的鸿蒙next三方库

友情链接

harmony-utils 一款功能丰富且极易上手的HarmonyOS工具库,借助众多实用工具类,致力于助力开发者迅速构建鸿蒙应用,能够满足各种不同的开发需求。

harmony-dialog 一款极为简单易用的零侵入弹窗,仅需一行代码即可轻松实现,无论在何处都能够轻松弹出。