weex 組件通信

官方文檔中其實就有介紹組件通信, 我這里寫下我自己的理解

1: 定義一個方法:
可以在任何組件中定義方法:

this.$on(type, handler)

type: 是監聽的自定義事件類型(官方解釋) , 我認為是你給方法起個標示的名字,在其他地方可以獲取到(了解的不夠深, 說錯了麻煩糾正下)
handler: 事件處理函數, 事件處理函數中第一個參數是事件對象$event, 詳見我的數據綁定

2: 其他的 ViewModel 中獲取這個方法, (此 ViewModel 中必須引用該組件)

xxx.$emit(type, detail);    //調用某某組件中的方法(type)

1: xxx , 指的是定義方法的組件,
2: detail, 是需要傳入的值

  • 格式:
    • 字符串(比如圖片路徑);
    • 對象或者數組(傳數字), 接受時需要JSON轉換 this.eventDetail = JSON.stringify(event.detail)

xxx獲取組件的方式

  • 子級ViewModel 獲取父級組件 使用this._parent
    <element name="foo">
    <template>
      <div>
        <image src="{{imageUrl}}" class="thumb" onclick="test"></image>
        <text>{{title}}</text>
      </div>
    </template>
    <style>
      .thumb { width: 200; height: 200; }
    </style>
    <script>
      module.exports = {
        data: {
          title: '',
          imageUrl: ''
        },
        methods: {
          test: function () {
            // Emit notify to parent
            this._parent.$emit('notify', {a: 1})
          }
        }
      }
    </script>
    

</element>
<template>
<div>
<foo title="Hello" image-url="https://gtms02.alicdn.com/tps/i2/TB1QHKjMXXXXXadXVXX20ySQVXX-512-512.png"></foo>
<text if="eventType">event: {{eventType}} - {{eventDetail}}</text>
</div>
</template>
<script>
module.exports = {
data: {
eventType: '',
eventDetail: {}
},
created: function () {
this.$on('notify', function(event) {
// When a notify comes, this handler will be run.
// event.detail will be {a: 1}
this.eventType = event.type
this.eventDetail = JSON.stringify(event.detail)
})
}
}
</script>

- 父級往子集傳值
父級中引用了子集, 需要子組件的id

this.$vm(id).$emit(type, detail)

id為子集的id 類似獲取節點

<element name="foo">
<template>
<div>
<image if="imageUrl" src="{{imageUrl}}" class="thumb"></image>
<text>Foo</text>
</div>
</template>
<style>
.thumb { width: 200; height: 200; }
</style>
<script>
module.exports = {
data: {
imageUrl: ''
},
created: function() {
this.$on('changeImage', function (e) {
this.imageUrl = e.detail
}.bind(this))
}
}
</script>
</element>
<template>
<div>
<foo id="sub"></foo>
<text onclick="test">click to update foo</text>
</div>
</template>
<script>
module.exports = {
methods: {
test: function (e) {
this.$vm('sub').$emit(
'changeImage',
'https://gtms02.alicdn.com/tps/i2/TB1QHKjMXXXXXadXVXX20ySQVXX-512-512.png'
)
}
}
}
</script>

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容