从微信小程序到鸿蒙js开发-swiper&animator&marquee
时间:2023-03-16 15:53:05
科技观察
更多内容请访问:与华为官方共建的鸿蒙技术社区https://harmonyos.51cto.com/#zz1、swiper中只能放置swiper-item轮播图微信小程序的swiper组件,除list以外的任何组件都可以放在鸿蒙js的swiper组件中,功能更强大。除了使用swiper结合自定义tabbar实现底部菜单的分页功能外,最常用的swiper就是首页的轮播图。swiper的属性可以看官方文档(https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-container-swiper-0000000000611533),开发者工具有bug在duration属性的代码提示是的,这里要填毫秒数:代码中swiper的最后四个属性填充默认值并且可以省略。2、image-animatorslideswiper是滚动轮播的效果,image-animator组件提供类似幻灯片的图片切换效果。它不支持任何子组件,只支持图像。官方文档(https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-components-basic-image-animator-0000001050066126)。image-animator的duration属性与swiper不同。支持给定单位,不给定单位默认为ms。而文档中写的“单次播放时间”其实就是一次播放完所有图片的时间,每张图片的显示时间平分。图像数组格式:"animatorImg":[{"src":"newyear1.jpeg"},{"src":"newyear2.jpeg"},{"src":"newyear3.jpeg"},{"src":"newyear4.jpeg"}],支持设置fixedsize="false",可以指定每张图片的大小数组长度、宽度、偏移量。"animatorImg":[{"src":"newyear1.jpeg","width":500"height":500},{"src":"newyear2.jpeg"},{"src":"newyear3.jpeg"},{"src":"newyear4.jpeg","width":400,"height":400,"top":100,"left":100}],3.marquee跑马灯组件提供跑马灯文字效果。文本从屏幕右侧出现并滚动到屏幕左侧。适用于滚动通知,或类似手表的布局。整体代码及效果图:hml:
css:.container{display:flex;flex-方向:列;宽度:100%;高度:1200px;}swiper{宽度:100%;高度:350px;}swiperimage{宽度:100%;高度:350px;}选框{margin-top:20px;margin-bottom:20px;width:100%;}image-animator{width:100%;height:550px;}js:(使用动静分离,详见下文)importfetchfrom'@system.fetch';exportdefault{data:{dataUrl:"http://milkytea.free.idcfengye.com/text/newyear.json",swipeImg:[],text:"",animatorImg:[]},onInit(){fetch.fetch({url:this.dataUrl,responseType:'json',success:res=>{letdata=JSON.parse(res.data);letimgUrl=data...].src;}this.swipeImg=swipeImg;this.text=data.text;this.animatorImg=animatorImg;}})}}4.Nginx动静分离在这个模块中,我没有把图片放在项目中directory其中js文件中连图片的url都没有写。一是现在app的功能越来越强大,占用的存储空间也越来越大。如果将所有的静态资源都存放在工程目录下,会增加空间占用。二是如果经常更换图片,或者更换服务器地址,写在代码里不太好维护。nginx服务器可以实现动静分离,使用本地路径作为静态资源服务器。基本配置如下,在nginx.conf中添加服务器:server{listen8500;server_namelocalhost;location/{root/Users/liuyufeng/image/;autoindexon;}location~^/(images|text|video|audio)/{root/Users/liuyufeng/image/;autoindexon;access_logon;expires30d;}}绑定本地文件夹“/Users/liuyufeng/image”到localhost:8500,按正则匹配“images”、“text”、“video”、“音频”四个子目录,分别存放图片、文字、视频、音频。重启nginx后,访问localhost:8500:本地目录变成静态资源服务器,不得不感叹nginx的强大。在鸿蒙项目中,不能一直请求localhost,所以用内网穿透,将本地服务器绑定域名即可。模块中的js代码只是通过请求静态资源中的newyear.json文件获取图片路径和文本数据,实现了动静分离。newyear.json{"imgUrl":"http://milkytea.free.idcfengye.com/images/newyear/","swipeImg":["swiper1.jpg","swiper2.jpg","swiper3.jpg"],"animatorImg":[{"src":"newyear1.jpeg","width":500,"height":500},{"src":"newyear2.jpeg"},{"src":"newyear3.jpeg"},{"src":"newyear4.jpeg","width":400,"height":400,"top":100,"left":100}],"text":"春节快乐假期,祝您节日快乐,家庭幸福,新年快乐!财源滚滚,生活幸福,生活每一天都美好,每个月都有高收入。”}更多资讯请访问:鸿蒙科技共建与华为正式社区https://harmonyos.51cto.com/#zz