加载中...

1.2.6 组件封装


经常我们会发现很多可复用的 weex 文件,这时候可以封装成 weex 组件。我们可以直接创建一个名为foo.we的文件,<foo>就是组件名。

  1. <!-- foo.we -->
  2. <template>
  3. <container style="flex-direction: row;">
  4. <image src="{{image}}"></image>
  5. <text>{{title}}</text>
  6. </container>
  7. </template>
  8. <script>
  9. module.exports = {
  10. data: {
  11. title: null,
  12. image: null
  13. }
  14. }
  15. </script>

foo.we 的也包含 <template><style><script>,定义好了后,直接用<foo>标签即可, 注意这里bar.wefoo.we是在同目录下哦,如下:

  1. <!-- bar.we -->
  2. <template>
  3. <foo title="..." image="..."></foo>
  4. </template>

组件嵌套

封装好的组件也支持嵌套,如下:

  1. <!-- somepath/foo.we -->
  2. <template>
  3. <container style="flex-direction: row;">
  4. <image src="{{image}}"></image>
  5. <text>{{title}}</text>
  6. </container>
  7. </template>
  8. <script>
  9. module.exports = {
  10. data: {
  11. // 这几个 key 必须明确写好,不论是上层数据传递下来还是内部修改数据才会被正常监听
  12. title: null,
  13. image: null
  14. }
  15. }
  16. </script>
  1. <!-- somepath/foo.list.we -->
  2. <template>
  3. <container>
  4. <text>{{description}}</text>
  5. <foo repeat="{{list}}" title="{{text}}" image="{{img}}"></foo>
  6. </container>
  7. </template>
  8. <script>
  9. module.exports = {
  10. data: {
  11. description: '',
  12. // 因为上层组件会通过 list 向下传递数据,所以这里需要把字段明确写好
  13. list: []
  14. }
  15. }
  16. </script>
  1. <!-- somepath/main.we -->
  2. <template>
  3. <foo-list list="{{list}}"></foo-list>
  4. </template>
  5. <script>
  6. module.exports = {
  7. data: {
  8. list: [
  9. {text: '...', img: '...'},
  10. {text: '...', img: '...'},
  11. {text: '...', img: '...'},
  12. ...
  13. ]
  14. }
  15. }
  16. </script>

main.we嵌套了<foo-list>, <foo-list>嵌套了<foo>

注意事项

  • 每个封装好的组件都有一个独立的<style>
  • 如果子组件有 id 属性,可以通过this.$vm(id)来访问子组件的上下文,并可以通过this.$el(id)来找节点。更多详见【如何找节点】
  • 更多模块间通信问题可以参考【 组件间如何通信】
  • 只有在 data 选项中明确写明的 key 才会被数据监听,不论是基于上层数据传递下来的场景还是内部修改数据的时候

第 1-1 条, 共 1 条.
zhangwei 2016-12-13 17:58:59
哦,这个要多练一下了回复