加载中...

1.5.2 组件定义


定义组件是通过一组选项来描述一个组件。这组选项总是被赋值给 <script> 标签中的 module.exports

  1. module.exports = {
  2. // a set of options here
  3. }

数据和方法

  1. module.exports = {
  2. data: function () {
  3. return {x: 1, y: 2}
  4. },
  5. methods: {
  6. doThis: function () {...},
  7. doThat: function () {...}
  8. },
  9. ...
  10. }

data 选项是一个函数,它返回这个视图模型可监听的数据对象。而 methods 是一个映射,其中包含所有视图模型的方法。

每个 datamethod 属性将被代理到视图模型实例中。所以,你能通过 this.x 读写数据,或者通过 this.doThis() 调用方法。

一个完整的例子:

  1. <template>
  2. <div style="width: {{w}}; height: {{h}}; background-color: red;" onclick="update"></div>
  3. </template>
  4. <script>
  5. module.exports = {
  6. data: function () {
  7. return {w: 750, h: 200}
  8. },
  9. methods: {
  10. update: function (e) {
  11. this.h += 200
  12. }
  13. }
  14. }
  15. </script>

事件

  1. module.exports = {
  2. data: ...,
  3. methods: {
  4. foo: function () {
  5. ...
  6. this.$emit('customtype1', data)
  7. }
  8. },
  9. events: {
  10. customtype1: function (e) {
  11. console.log(e.type, e.detail)
  12. }
  13. },
  14. ...
  15. }

events 选项允许你在视图模型被创建时注册自定义事件。然后,它会监听这些类型的事件,并通过函数类型的值处理它们。

Weex 会把一个事件对象作为第一个参数传递给其绑定的事件,这个事件对象在 e.detail 中包含事件数据。

生命周期

  1. module.exports = {
  2. data: ...,
  3. methods: ...,
  4. init: function () {
  5. console.log('ViewModel constructor begins')
  6. },
  7. created: function () {
  8. console.log('Data observation finished')
  9. },
  10. ready: function () {
  11. console.log('Virtual DOM finished')
  12. },
  13. ...
  14. }

Weex 视图模型现在支持生命周期内的钩子函数,这些钩子函数能被写为组件选项:

  • init: 在视图模型的构造函数开始调用时激活;
  • created: 当视图模型监听默认数据,但还未编译模板时激活;
  • ready: 当视图模型监听默认数据并且编译模板生成虚拟DOM后被激活。

注意:当 methodsevents 或生命周期方法作为参数传递给别的函数时,务必确认函数执行时的上下文符合您的预期,例如:

  1. module.exports = {
  2. data: function () {
  3. return {x: 1, y: 2}
  4. },
  5. ready: function () {
  6. // `undefined`
  7. // 因为上下文发生了变化
  8. this.foo(this.bar)
  9. // `1`
  10. // 正确绑定上下文之后可以得到预期的值
  11. this.foo(this.bar.bind(this))
  12. },
  13. methods: {
  14. foo: function (fn) {
  15. return fn()
  16. },
  17. bar: function () {
  18. return this.x
  19. }
  20. }
  21. }

还没有评论.