子-父 通信
子組件可以使用this.$dispatch([String type], [Object detail]) 方法傳遞消息給父組件。
第一個(gè)參數(shù)定義消息類型,第二個(gè)參數(shù)為消息對(duì)象。如果父組件中的任何子組件使用$on([String type], [Function callback])注冊(cè)監(jiān)聽事件,則回調(diào)執(zhí)行第一個(gè)參數(shù),參數(shù)中的 detail屬性是消息數(shù)據(jù)。
<we-element name="foo">
<template>
<div>
<image src="{{imageUrl}}" onclick="test"></image>
<text>{{title}}</text>
</div>
</template>
<script>
module.exports = {
data: {
title: '',
imageUrl: ''
},
methods: {
test: function () {
this.$dispatch('notify', {a: 1})
}
}
}
</script>
</we-element>
<template>
<foo title="..." image-url="..."></foo>
</template>
<script>
module.exports = {
created: function () {
this.$on('notify', function(e) {
// when <foo> image tag be clicked ,the function will be executing.
// e.detail is `{a: 1}`
})
}
}
</script>
父 - 子 通信
父組件可以使用 this.$([String id]) 來獲取子組件的上下文。你可以使用上下文對(duì)象訪問子組件的信息。
<we-element name="foo">
<template>
<div>
<image src="{{imageUrl}}"></image>
<text>{{title}}</text>
</div>
</template>
<script>
module.exports = {
data: {
title: '',
imageUrl: ''
},
methods: {
setTitle: function (t) {
this.title = t
}
}
}
</script>
</we-element>
<template>
<div>
<text onclick="test">click to update foo</text>
<foo id="fooEl" title="..." image-url="..."></foo>
</div>
</template>
<script>
module.exports = {
methods: {
test: function (e) {
var foo = this.$('fooEl')
foo.setTitle('...')
foo.imageUrl = '...'
}
}
}
</script>
父 - 子(多子)通信
父組件可以使用this.$broadcast([String type], [Object detail]) 廣播消息給所有子組件。
案例:
<we-element name="bar">
<template>
<div>
<image src="{{imageUrl}}"></image>
</div>
</template>
<script>
module.exports = {
data: {
imageUrl: ''
},
created: function() {
var self = this
this.$on('changeImage', function(e) {
self.imageUrl = e.detail.imageUrl
})
}
}
</script>
</we-element>
<we-element name="foo">
<template>
<div>
<bar></bar>
<text>{{title}}</text>
</div>
</template>
<script>
module.exports = {
data: {
title: ''
},
created: function() {
var self = this
this.$on('changeTitle', function(e) {
self.title = e.detail.title
})
}
}
</script>
</we-element>
<template>
<div>
<text onclick="test">click to update foo</text>
<foo></foo>
<foo></foo>
</div>
</template>
<script>
module.exports = {
methods: {
test: function (e) {
this.$broadcast('changeTitle', {
title: '...'
})
this.$broadcast('changeImage', {
imageUrl: '...'
})
}
}
}
</script>
兄弟間通信
兄弟組件間通過公共的父組件作為橋梁來傳遞消息。
案例:
<we-element name="foo">
<template>...</template>
<script>
module.exports = {
methods: {
callbar: function () {
this.$dispatch('callbar', {a: 1})
}
}
}
</script>
</we-element>
<we-element name="bar">
<template>...</template>
<script>
module.exports = {
created: function() {
this.$on('callbar', function(e) {
// e.detail.a
})
}
}
</script>
</we-element>
<template>
<div>
<foo></foo>
<bar></bar>
</div>
</template>
<script>
module.exports = {
created: function () {
var self = this
this.$on('callbar', function(e) {
self.$broadcast('callbar', e.detail)
})
}
}
</script>