微信小程序 WXML提供了import和include引用方式
作者: --时间: 2025-05-17 19:48:43 阅读量:

使用import和include引用方式的微信小程序开发

微信小程序WXML提供了两种文件引用方式:importinclude,方便开发者模块化管理代码。


1. 使用import引用template

import可以在当前文件中嵌入目标文件定义的template,使得这个template可以在当前文件内被使用。

以在item.wxml中定义一个名为itemtemplate为例:

  
    <!-- item.wxml -->
    <template name="item">
      <text>{{text}}</text>
    </template>
  

index.wxml中引用item.wxml,可以使用item模板:

  
    <import src="item.wxml"/>
    <template is="item" data="{{text: 'forbar'}}"/>
  

1.1 import的作用域

import有作用域的概念。即只会import目标文件中定义的template,而不会import目标文件import的template

例如:C import B,B import A,在C中可以使用B定义的template,在B中可以使用A定义的template,但是C不能使用A定义的template

  
    <!--A.wxml-->
    <template name="A">
      <text>A template</text>
    </template>
  
  
    <!--B.wxml-->
    <import src="a.wxml"/>
    <template name="B">
      <text>B template</text>
    </template>
  
  
    <!--C.wxml-->
    <import src="b.wxml"/>
    <template is="A"/> <!-- Error! Can not use tempalte when not import A. -->
    <template is="B"/>
  

2. 使用include引用代码片段

include可以将目标文件(除了<template/>)的整个代码引入到当前位置。这种方式适合在多个页面中使用相同的代码片段,如页面头部和底部布局等。

例如,在header.wxml中定义页面头部布局代码片段:
  
    <!-- header.wxml -->
    <view>header</view>
  
同样,在footer.wxml中定义页面底部布局代码片段:
  
    <!-- footer.wxml -->
    <view>footer</view>
  
index.wxml中使用include引入头部和底部的代码片段:
  。。。。。。
一套系统全搞定
  • 商家管理
  • 商品管理
  • 订单管理
  • 会员管理
  • 营销中心
  • 供应链入驻
  • 财务管理
  • 支付分账
  • 商城直播
免费试用
更多产品任你选
B2B2C多用户商城系统

类天猫&京东模式系统

了解更多
B2B2B电商交易系统

全渠道订货/采购及经销商管
理数字化系统

了解更多
S2B2B电商交易系统

上下游资源整合数字化解决方

了解更多
企业集采商城系统

中大型企业数字化采购与交易
系统

了解更多
员工福利商城系统

集福利管理、发放于一体的员
工福利商城

了解更多

电话咨询 微信咨询 0元开店