# 小程序动态组件使用 (店铺装修)

  • 通过后台配置装修小程序首页页面
  • 小程序怎么动态使用组件,类似VUE component
  • 另外我会重新开一个专题重点介绍 [店铺装修] 如何去实现, 毕竟这是一个综合应用

# 后台配置小程序需要的组件


xcooo

# Vue动态组件用法

要实现装修的需求,其实就是十几个乃至数十个组件化的组件跟搭建积木一样搭建起来的,要做到这一步首先我们要知道这个搭积木的每一层要用怎样的组件, 例如第一层你要用到轮播图, 第二层你要用到导航条,又或者你两层都要用到轮播图, 这个就需要跟后端协商好数据结构,使用动态组件中的is来判断组件

# 1.首先先挂载所有的组件:


xcooo

# 2.定义数组结构

后面就是跟后端协商好数据结构后用:is根据后端发挥的name字段进行判断 类似下面的数据结构

    items: [
      {
        sort: 0,
        name: "MCarouselImg",
        data: {
          name:'星城哈哈'
        },
      },
      {
        sort: 1,
        name: "MCategoryList",
        data: {},
      },
    ],
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 3.使用动态组件

<component :is="items.name" v-for="(items,index) in  items" :key="index"></component>
1

# 小程序动态组件用法

# 效果展示 (通过后台配置, 动态展示页面)


xcooo

# 先定义 4 个子组件进行演示


xcooo

# 定义父组件, 引入子组件 (基本可以实现上面的效果了)

# 代码实现

json

{
  "usingComponents": {
    "MCarouselImg":"../../components/MCarouselImg/index",
    "MCategoryList":"../../components/MCategoryList/index",
    "MRecommendGoods":"../../components/MRecommendGoods/index",
    "MText":"../../components/MText/index"
  }
}
1
2
3
4
5
6
7
8

WXML

<view>
  <view class="text">我是动态组件展示页面</view>
  <!-- 轮播图 -->
  <template name="MCarouselImg">
    <MCarouselImg data="{{data}}"></MCarouselImg>
  </template>
  <!-- 分类视图 -->
  <template name="MCategoryList">
    <MCategoryList></MCategoryList>
  </template>
  <!-- 推荐商品 -->
  <template name="MRecommendGoods">
    <MRecommendGoods></MRecommendGoods>
  </template>
  <!-- 纯文本 -->
  <template name="MText">
    <MText></MText>
  </template>
  
  <!-- 使用动态组件, 并传递参数给子组件 -->
  <block wx:for="{{items}}" wx:key="*this">
    <template is="{{item.name}}"  data="{{...item}}"></template>
  </block>
</view>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

Js

  • 假如这是从后台请求过来的数据, 重点是 name 这个字段, 必须和小程序对应的模板名称一致
  • 我也演示了 如何将请求过来的参数传递给 子组件, 请看上面的wxml 和 效果图
// pages/ComponentList/index.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    items: [
      {
        sort: 0,
        name: "MCarouselImg",
        data: {
          name:'星城哈哈'
        },
      },
      {
        sort: 1,
        name: "MCategoryList",
        data: {},
      },
      {
        sort: 2,
        name: "MCarouselImg",
        data: {
          name:'我是父组件的数据'
        },
      },
      {
        sort: 3,
        name: "MText",
        data: {},
      },
      {
        sort: 4,
        name: "MText",
        data: {},
      },
    ],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {},
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

# 参考文章

上次更新: 2020/10/27 下午11:58:10