Learn the template and reference of WeChat applet WXML

This post is a note for 9 hours of learning to complete the development of WeChat applets
. Documentation : templates, applets , references, applets

1. Template: Use the template tag to define your own code snippets in the template
<!-- index.wxml -->
<template name="tempItem">
    <view>
        <view>收件人:{
   
   {name}}</view>
        <view>联系方式:{
   
   {phone}}</view>
        <view>地址:{
   
   {address}}</view>
    </view>
</template>

<template is="tempItem" data="{
     
     {...item}}"></template>

nameThe attribute is the name of the template, and isthe attribute declares which template we are using. { {...item}}The three dots in the front are the spread operator in es6 syntax, which can deconstruct and assign objects or arrays.

//index.js
Page({
    data:{
        item:{
            name:"张三",
            phone:"18888888888",
            address:"中国"
        }
    }
})

Write picture description here

In addition, isattributes can also do some dynamic data binding.

<template name="odd">
  <view> odd </view>
</template>
<template name="even">
  <view> even </view>
</template>

<block wx:for="{
     
     {[1, 2, 3, 4, 5]}}">
    <template is="{
     
     {item % 2 == 0 ? 'even' : 'odd'}}"/>
</block>

Write picture description here

2. File reference: import and include

Two ways to reference templates: the difference between include and import
: includeonly the content in the file except the template content will be referenced, importand only the content in the template in the file will be referenced, and the data will be dynamically passed in, isindicating the referenced template name, dataindicating the incoming Template data.

import
<!--index.wxml -->
<import src="a.wxml"></import>
<template is="a"></template>
<!-- a.wxml -->
<view>Hello,world</view>
<template name="a">
    Hello,World!
</template>

Write picture description here
The scope of import
import has the concept of scope, that is, it will only import the template defined in the target file, but not the template imported by the target file.

For example: C import B, B import A, the template defined by B can be used in C, the template defined by A can be used in B, but the template defined by A cannot be used in C.

This is to avoid the problem of referencing infinite loops in templates.

<!--index.wxml-->
<import src="a.wxml"></import>
<template is="a"></template>
<!--a.wxml-->
<import src="b.wxml"/>
<template name="a">
    This is a.wxml
</template>
<!--b.wxml-->
<template name="b">
    This is b.wxml
</template>

Write picture description here

include
<!--index.wxml-->
<include src="a.wxml" />
<template is="a">
</template>
<!--a.wxml-->
<template name="a">
    <view>
        This is a.wxml
    </view>
</template>
<view>Hello,world</view>

Write picture description here

Guess you like

Origin blog.csdn.net/sriting/article/details/79968376