# 组件

熟悉自定义组件的开发,了解父子组件之间的通信方式,如:props,data

通过本节,你将学会:

# 组件自定义

开发页面时开发者必须用到 Native 组件,如:textdiv,这些组件是由各平台 Native 底层渲染出来的;如果开发一个复杂的页面,开发者把所有的 UI 部分写在一个文件的<template>,那代码的可维护性将会很低,并且模块之间容易产生不必要的耦合关系

为了更好的组织逻辑与代码,可以把页面按照功能拆成多个模块,每个模块负责其中的一个功能部分,最后页面将这些模块引入管理起来,传递业务与配置数据完成代码分离,那么这就是自定义组件的意义

自定义组件是一个开发者编写的组件,使用起来和 Native 一样,最终按照组件的<template>来渲染;同时开发起来又和页面一样,拥有 ViewModel 实现对数据、事件、方法的管理

这么来看,页面也是一种特殊的自定义组件,无需引入即可使用,同时服务于整个页面

示例如下:

<template>
  <div class="tutorial-page">
    <text class="tutorial-title">自定义组件:</text>
    <text>{{ say }}</text>
    <text>{{ obj.name }}</text>
  </div>
</template>

<style lang="less">
  .tutorial-page {
    flex-direction: column;
    padding-top: 20px;
  }
  .tutorial-title {
      font-weight: bold;
  }  
</style>

<script>
  // 子组件
  export default {
    data: {
      say: 'hello',
      obj: {
        name: 'quickApp'
      }
    },
    /*
      data(){
      return {
          say:'hello',
          obj:{
            name:'quickApp'
          }
      }
      },
    */
    onInit() {
      console.log('我是子组件')
    }
  }
</script>
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

自定义组件中数据模型只能使用data 属性,data 类型可以是 Object 或 Function。如果是函数,返回结果必须是对象。

# 组件引入

快应用中是通过<import>标签引入组件,如下面代码所示

<import name="XXX" src="XXX"></import>
1

<import>标签中的的src属性指定自定义组件的地址,name属性指定在父组件中引用该组件时使用的标签名称

示例如下:

<import name="comp-part1" src="./part1"></import>

<template>
  <div class="tutorial-page">
    <text class="tutorial-title">引入组件:</text>
    <comp-part1></comp-part1>
  </div>
</template>

<style lang="less">
  .tutorial-page {
    flex-direction: column;
    padding: 20px 10px;
  }
  .tutorial-title {
      font-weight: bold;
  }
</style>

<script>
  // 父组件
  export default {
    data: {},
    onInit() {
      console.log('引入组件')
    }
  }
</script>
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

# 父子组件通信

# 父组件通过 Prop 向子组件传递数据

父组件向子组件传递数据,通过在子组件的props属性中声明对外暴露的属性名称,然后在组件引用标签上声明传递的父组件数据,详见Props

示例如下:

<!-- 子组件 -->
<template>
  <div class="child-demo">
    <text class="title">子组件:</text>
    <text>{{ say }}</text>
    <text>{{ propObject.name }}</text>
  </div>
</template>
<script>
  export default {
    props: ['say', 'propObject'],
    onInit() {
      console.info(`外部传递的数据:`, this.say, this.propObject)
    }
  }
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!-- 父组件 -->
<import name="comp" src="./comp"></import>
<template>
  <div class="parent-demo">
    <comp say="{{say}}" prop-object="{{obj}}"></comp>
  </div>
</template>
<script>
  export default {
    data: {
      say:'hello'
      obj:{
        name:'child-demo'
      }
    }
  }
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17