微信小程序 引入公共页面的几种情况 - 新闻资讯 - 云南小程序开发|云南软件开发|云南网站建设-昆明葵宇信息科技有限公司

159-8711-8523

云南网建设/小程序开发/软件开发

知识

不管是网站,软件还是小程序,都要直接或间接能为您产生价值,我们在追求其视觉表现的同时,更侧重于功能的便捷,营销的便利,运营的高效,让网站成为营销工具,让软件能切实提升企业内部管理水平和效率。优秀的程序为后期升级提供便捷的支持!

您当前位置>首页 » 新闻资讯 » 小程序相关 >

微信小程序 引入公共页面的几种情况

发表时间:2021-3-31

发布人:葵宇科技

浏览次数:65

1、不带参数

首先在pages文件夹中新建一个template文件夹,文件夹中新建一个template.wxml文件,代码如下


<template name="msgItem">
<view>
<text>This is template.wxml文件,我是一个模板text>
view>
template>

然后我们书写我们所要调用template的页面index.wxml



<import src ="../template/template.wxml"/>
  <view>This is index.wxmlview>
<template is="msgItem"/>

注意:

(1)index.wxml中template 标签的is属性与template.wxml中template 标签的name属性值相同

(2)index.wxml文件中要通过import标签声明需要使用的模板文件

运行效果:

2、带参数

首先,修改template.wxml文件,我们给模板添加三个字段,修改后代码如下

<template name="msgItem">
<view>
<text>This is template.wxml文件,我是一个模板text>
<view>
<text> {{index}}: {{msg1}} text>
<text> {{msg2}} text>
view>
view>
template>

接下来我们在index.wxml中传递模板中所需要的三个参数,修改后的代码如下:



<import src ="../template/template.wxml"/>
<view>This is index.wxmlview>
<template is="msgItem" data="{{index:1,msg1:'msg1数据',msg2:'msg2数据'}}"/>

运行效果:

3、列表item模板

接下来我们就通过一种常见的情况列表数据来使用模板,增加对模板的认知,直接上修改过的代码:

//index.js
Page({
data: {
list:[
{ name: '张三', age: 15 },
{ name: '李四', age: 25 },
{ name: '王五', age: 18 },
{ name: '赵六', age: 19 },
]
}
})


<import src ="../template/template.wxml"/>
<view>This is index.wxmlview>
<view wx:for="{{list}}">
<template is="msgItem" data="{{name:item.name,age:item.age}}"/>
view>

<template name="msgItem">
<view>
<text> name: {{name}} text>
<text> age: {{age}}text>
view>
template>

运行效果:

4、使用模板样式

接下来我们就给模板增加样式文件,然后在需要调用模板的地方使用该样式。

首先在pages/template文件夹中新建一个template.wxss文件,然后对模板文件,添加一个简单样式。


<template name="msgItem">
<view class="template_style">
<text> name: {{name}} text>
<text class="template_age_style"> age: {{age}}text>
view>
template>
/* pages/template/template.wxss */
.template_style{
border-bottom: solid 2px #999999;
padding: 5px;
font-size: 18px;
color: #000000;
}
.template_age_style{
color: #666666;
font-size: 14px;
}

我们的样式文件已经创建好了,接下来在index.wxml中引入该样式文件。

/index.wxss/
@import "../template/template.wxss";
运行效果:

5、调用不同的模板

有时候,我们有这样的需求,那就是同一个列表中,item数据不同,可能他的样式也是有很大的区别,所以我们使用的模板也会对应不相同,接下来我们就来实现这样需求的小Demo:
首先修改了一下template.wxml,原本该文件中只有一个template,现在我们创建了两个,新增的template仅仅多了一行代码,当然了实际开发中,需求会比这个难很多,在这里只是为了实现Demo。


<template name="msgItem">
<view class="template_style">
<text> name: {{name}} text>
<text class="template_age_style"> age: {{age}}text>
view>
template>
<template name="msgItem2">
<view class="template_style">
<text> name: {{name}} text>
<text class="template_age_style"> age: {{age}}text>
<text>我是一个未成年text>>
view>
template>

接下来我们在index.wxml中通过age字段调用不同的模板:



<import src ="../template/template.wxml"/>
<view>This is index.wxmlview>
<view wx:for="{{list}}">
<template is="{{item.age >= 18 ? 'msgItem' : 'msgItem2'}}" data="{{name:item.name,age:item.age}}"/>
view>

运行效果: 

相关案例查看更多