目录

template模板

类似HTML的标签语言,结合基础组件、自定义组件、事件,构建出页面的结构。

模板中只能有1个根节点,如:div;请不要在<template>下存在多个根节点,也不要使用block作为根节点。

数据绑定

<template>
    <text> {{message}} </text>
</template>
<script>
    module.exports= {
        data: {
            message: 'Hello World!'
        }
    }
</script>

内联样式支持数据绑定,支持样式如下:

{{'height:'+height+'px'}}

事件绑定

<template>
    <div>
        <!-- 正常格式 -->
        <div onclick="press"></div>
        <!-- 缩写 -->
        <div @click="press"></div>
    </div>
</template>
<script>
    module.exports= {
        press: function(e) {
        this.title = 'Hello'
    }
  }
</script>

事件回调支持的写法(其中{{}}可以省略):

回调函数被调用时,会在参数列表末尾自动添加一个evt参数,通过evt参数访问回调事件相关上下文数据(数据内容具体参看组件回调事件说明),例如点击事件的点击位置x,y。

[h2]传常量参数

<template>
    <div class="demo-page">
        <text for="{{list}}" onclick="handle($idx,$item)">{{$item}}</text>
    </div>
</template>
<style>
.demo-page{
    flex-direction: column;
    align-items: center;
}
</style>
<script>
export default {
    private: {
        list:[1,2,3,4,5]
    },
    handle(idx,item,evt){
        console.log("idx:"+idx);
        console.log("item: "+item);
        console.log('evt: '+JSON.stringify(evt));
    }
}
</script>

点击最后一个text后,效果图如下:

[h2]传变量参数

<template>
    <div class="demo-page">
        <text for="{{list}}" onclick="handle(total,$item)">{{$item}}</text>
    </div>
</template>
<style>
.demo-page{
    flex-direction: column;
    align-items: center;
}
</style>
<script>
export default {
    private: {
        list:[1,2,3,4,5],
        total:0
    },
    handle(total,num,evt){
        console.log("total:"+total);
        console.log("num: "+num);
        console.log('evt: '+JSON.stringify(evt));
    }
}
</script>

效果图如下:

列表渲染

<template>
    <div class="list-container">
      <div for="{{list}}" tid="id">
         <text>{{$idx}}</text>
         <text>{{$item.id}}</text>
      </div>
      <div for="value in 7">
         <text>{{value}}</text>
      </div>
    </div>
</template>
<script>
    module.exports= {
        data: {
            list: [{id:1}, {id:2}]
        }
    }
</script>

标签中的tid用于指定作为定义数组元素唯一Id的字段名,如果没有指定,则默认采用数组索引($idx)作为唯一Id;tid的作用是为了元素节点重用,优化for循环的重绘效率。例如 tid="id" 表示$item.id作为数组元素的唯一Id。for循环支持的写法(其中{{}}可以省略):

  • tid指定的数据属性必须存在,否则可能引起运行异常。
  • tid指定的数据属性要保证唯一,如果发生重复,可能会造成性能问题。

条件渲染

分为2种:if/elif/else和show。它们的区别在于:if为false时,组件会从VDOM中移除,而show仅仅是渲染时不可见,组件依然存在于VDOM中。if/elif/else节点必须是相邻的兄弟节点,否则无法通过编译。

<template>
    <div>
        <text if="{{show}}"> Hello-1 </text>
        <text elif="{{display}}"> Hello-2 </text>
        <text else> Hello-3 </text>
    </div>
</template>
<script>
    module.exports= {
        data: {
            show: false,
            display: true
        }
    }
</script>

show等同于display=none,目前只用于系统原生组件,对自定义组件不生效。自定义组件可以通过props传入参数,在自己内部使用show来控制是否可见。

<template>
  <div>
    <text show="{{visible}}"> Hello </text>
  </div>
</template>
<script>
    module.exports= {
        data: {
            visible: false
        }
    }
</script>

逻辑控制块

可以使用<block>实现更为灵活的循环/条件渲染; 注意<block>目前只支持for和if/elif/else属性,如果没有指定任何属性,<block>则在构建时被当作“透明”节点对待,其子节点被添加到<block>的父节点上。

<template>
    <list>
        <block for="cities">
            <list-item type="city">
                <text>{{$item.name}}</text>
            </list-item>
            <block for="$item.spots" if="false">
                <list-item type="spot">
                    <text>{{$item.address}}</text>
                </list-item>
            </block>
        </block>
    </list>
</template>
<script>
    module.exports= {
        data: {
            cities: [
                {name:"beijing", spots:[{name:"XXX",address:"XXX"},{name:"XXX",address:"XXX"}]},
                {name:"shanghai", spots:[{name:"XXX",address:"XXX"},{name:"XXX",address:"XXX"}]}
            ]
        }
    }
</script>

引入自定义组件

快应用中通过<import>标签引入组件。

示例代码如下:

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

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

<script>
  // 父组件
  export default {
    private: {},
    onInit() {
      this.$page.setTitleBar({ text: '引入组件' })
    }
  }
</script>
  • 组件名不区分大小写,默认统一采用小写。
  • 通过(on|@)event1语法绑定自定义子组件的event1事件,触发事件childVm.$emit('event1', { params: '传递参数' })时执行父组件的方法:bindParentVmMethod1。
  • 标签上声明事件名称采用-连接,不要使用驼峰式,来做响应与方法的关联,即:使用event-type1表示绑定eventType1事件。

[h2]父子组件通信

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

父页面:

<import name="comp-part1" src="../part1/part1.ux"></import>
<!-- 父组件 -->
<template>
  <div class="parent-demo">
    <comp-part1 say="{{say}}" prop-object="{{obj}}"></comp-part1>
  </div>
</template>
<script>
  export default {
    private: {
      say: 'hello',
      obj: {
        name: 'child-demo'
      }
    }
  }
</script>

子页面:

<!-- 子组件 -->
<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>

当子组件对数据进行改造后,把最终数据交给父组件,有以下三种方法:

示例代码如下。

父页面:

<!-- 父组件 -->
<import name="comp1" src="./com/comp1.ux"></import>
<import name="comp2" src="./com/comp2.ux"></import>
<import name="comp3" src="./com/comp3.ux"></import>
<template>
  <div class="parent-demo">
    <text>我是父组件count:{{ count }}</text>
    <comp1 count="{{count}}" onemit-evt="emitEvt"></comp1>
    <text>我是父组件num:{{ num }}</text>
    <comp2 num="{{num}}"></comp2>
    <text>我是父组件age:{{ age }}</text>
    <input type="button" onclick="evtTypeEmit" value="触发$broadcast()"></input>
    <comp3></comp3>
  </div>
</template>
<script>
    export default {
        private: {
            count: 20,
            num: 20,
            age: 18
        },
        onInit() {
            this.$on('dispatchEvt', this.dispatchEvt) },
        emitEvt(evt) {
            this.count = evt.detail.count},
        dispatchEvt(evt) {
            this.num = evt.detail.num },
        evtTypeEmit() {
            this.$broadcast('broadevt', {
                age: 19}) },}
</script>

子页面1:

<!-- comp1 -->
<template>
  <div class="child-demo">
    <text>我是子组件一count:{{compCount}}</text>
    <input type="button" onclick="addHandler" value="add"></input>
  </div>
</template>
<script>
    export default {
        props: ['count'],
        data() {
            return {
                compCount: this.count
            }
        },
        addHandler() {
            this.compCount++
            this.$emit('emitEvt', {
                count: this.compCount
            })
        },
    }
</script>

子页面2:

<!-- comp2 -->
<template>
  <div class="child-demo">
    <text>我是子组件二num:{{compNum}}</text>
    <input type="button" onclick='delHandler' value='del'></input>
  </div>
</template>
<script>
  export default {
    props: ['num'],
    data(){
        return{
            compNum:this.num
        }
    },
    delHandler(){
        this.compNum --
        this.$dispatch('dispatchEvt',{
            num:this.compNum
        })
    },
  }
</script>

子页面3:

<!-- comp3 -->
<template>
  <div class="child-demo">
    <text>我是子组件三age:{{compAge}}</text>
  </div>
</template>
<script>
    export default {
        props: [],
        data() {
            return {
                compAge: null
            }
        },
        onInit() {
            this.$on('broadevt', this.broadevt)
        },
        broadevt(evt) {
            this.compAge = evt.detail.age
        }
    }
</script>

插入自定义组件

组件中通过标签来定义子组件插入位置,例如:

组件com-a的模板定义为:

<template>
    <div>
      <text>header</text>
      <slot>default content</slot>
      <text>footer</text>
    <div>
</template>

在页面使用组件comA,定义如下:

<import name="comp-a" src="./comp-a"></import>
<template>
    <com-a>
      <text>body</text>
    </com-a>
</template>

则在页面渲染时,组件comA变为:

<div>
  <text>header</text>
  <text>body</text>
  <text>footer</text>
</div>

动态组件(1070+)

在没有动态组件功能时,开发者往往通过if/elif/else指令来实现需求。现在使用动态组件,开发者可以灵活控制模板中需要渲染哪个自定义组件。

如下代码所示,通过component逻辑组件与对应的is属性来判断运行时到底渲染哪个组件。

<import name="part1" src="./compA"></import>
<import name="part2" src="./compB"></import>
<import name="part3" src="./compC"></import>
<template>
  <div class="container">
    <div class="page-title-wrap">
      <text class="page-title">{{componentName}}</text>
    </div>
    <div class="tutorial-page">
      <div class="item-content">
        <component is="{{who}}"></component>
      </div>
      <input type="button" class="btnComponent" onclick="onchangeComponent"
value="changeComponent" />
    </div>
  </div>
</template>
<script>
  export default {
    data: {
      componentName: 'Component dynamic component',
      who: 'part1'
    },
    onchangeComponent() {
      if (this.who === 'part1') {
        this.who = 'part2'
      } else if (this.who === 'part2') {
        this.who = 'part3'
      } else {
        this.who = 'part1'
      }
    }
  }
</script>

过滤器

在 hap-toolkit 0.4.0 之后,允许自定义过滤器,可用于文本格式化。

过滤器是一个函数,在页面导出的对象中定义,如下面的 capitalize:

<script>
    export default {
        private: {
            message: 'hello'
        },
        capitalize(value) {
            if (!value) return ''
            value = value.toString()
           return value.charAt(0).toUpperCase() + value.slice(1)
        }
    }
</script>

使用过滤器时,应该添加到表达式的尾部,由管道符号指示。 和 vue 过滤器类似,其形式如下:

{{ message | capitalize }}

在以上示例中,过滤器函数接收表达式的值作为第一个参数,即capitalize 过滤器函数将会收到 message 的值作为第一个参数,完整示例如下:

<template>
    <div>
        <text>{{ message | capitalize }}</text>
    </div>
</template>
<script>
export default {
    private: {
        message: 'hello'
    },
    capitalize(value) {
        if (!value) return ''
            value = value.toString()
            return value.charAt(0).toUpperCase() + value.slice(1)
        }
    }
</script>

过滤器还有以下两种用法。

[h2]过滤器可以串联

在以下示例中,filterA 被定义为接收单个参数的过滤器函数,表达式 message 的值将作为参数传入到函数中。然后继续调用同样被定义为接收单个参数的过滤器函数 filterB,将 filterA 的结果传递到 filterB 中:

{{ message | filterA | filterB }}

[h2]过滤器可以接收多个参数

在以下示例中,filterA 被定义为接收三个参数的过滤器函数。其中 message 的值作为第一个参数,普通字符串 'arg1' 作为第二个参数,表达式 arg2 的值作为第三个参数。

{{ message | filterA('arg1', arg2) }}

相关链接

[h2]FAQ

[h2]案例