微信小程序——数据的渲染和模板与样式的复用
前言
在网页前端H5编程中,我们已经知道存在模板的复用等功能,大大的提高了开发的效率,在微信小程序中,也有同样的模板复用和样式复用。
数据渲染
在讲模板和样式复用之前,我们先讲讲微信小程序特有的数据渲染,在H5我们是通过DOM来操作渲染内容的,但是在微信小程序的前端中我们只能通过数据渲染来完成数据加载到UI上。
前端代码:
<swiper indicator-dots="true" autoplay="true" class="swiper">
<block wx:for="{{bannerArr}}">
<swiper-item class="banner-item" bindtap="onProductsItemTap" data-id="{{item.key_word}}">
<image class="item-image" src="{{item.img.url}}" mode="aspectFill" />
</swiper-item>
</block>
</swiper>
后端代码:
onLoad: function (options) {
this._onloadData();
},
_onloadData:function(){
var that = this;
var id=1;
home.getBannerData(id,res=>{
console.log(res)
that.setData({
bannerArr:res,
})
});
},
我们通过setData将服务端返回的res赋给bannerArr,然后在前端bannerArr上进行循环渲染,用{{item.*****}}来渲染内容。
具体使用如下:
这是我res返回的结果,此时我们将其赋给了bannerArr,然后bannerArr在前端循环渲染数据,每次循环的内容用item来表示,所以要取到json里面的img只需要item.img.url即可取到
Wxml的模板复用
<template name="products">
<view class="products-box">
<block wx:for="{{productsArr}}">
<view class="products-item" bindtap="onProductsItemTap" data-id=" {{item.id}}">
<image class="products-image" src="{{item.main_img_url}}" mode="aspectFill"></image>
<view class="products-item-bottom">
<text class="name">{{item.name}}</text>
<view class="price">¥{{item.price}}</view>
</view>
</view>
</block>
</view>
</template>
这是定义在pages\tpls\products目录下的文件模板
注意此处模板文件里面的{{productsArr}}
<import src="../tpls/products/products-tpl.wxml"/>
<view class="home-main-products">
<view class="home-main-header">最近新品</view>
<template is="products" data="{{productsArr:productsArr}}"/>
</view>
我们可以通过这样的形式在需要用到的地方进行引入is="products"
引入后要将数据渲染给模板文件data="{{productsArr:productsArr}}"
可以理解为js层传来的数据作为value,模板文件的标签数据作为key
Wxss的样式复用与全局样式
Wxss的样式复用
同样的Wxss的复用不涉及到数据渲染就更简单了。直接在目标wxss下引用即可。
@import "../tpls/base.wxss";
@import "../tpls/products/products-tpl.wxss";
全局样式
全局样式是app.wxss文件,里面设置默认全局,无需一个个引用,更加方便。
/**app.wxss**/
.container {
height: 100%;
flex-direction: column;
align-items: center;
justify-content: space-between;
box-sizing: border-box;
background-color: #fff;
font-family: "PingFang SC", "Helvetica Neue", Helvetica, Arial, "Hiragino Sans GB", "Microsoft Yahei", ���ź�, STHeiti, ����ϸ��, sans-serif;
}
Neue", Helvetica, Arial, “Hiragino Sans GB”, “Microsoft Yahei”, ���ź�, STHeiti, ����ϸ��, sans-serif;
}