<!DOCTYPE html> |
<html> |
<head> |
<title></title> |
<script src= "https://unpkg.com/vue" ></script> |
<script src= "https://cdn.bootcss.com/vue-router/2.4.0/vue-router.js" ></script> |
</head> |
<body> |
<div id= 'app' > |
<foo></foo> |
<hr> |
<bar></bar> |
</div> |
<script type= "text/javascript" > |
// 注册一个空的 Vue 实例,作为 ‘中转站’ |
var eventBus = new Vue({}) |
// foo 组件 |
var foo = { |
template: '<div><p>the count of foo is {{fooCount}}</p>' + |
'<button @click="addBar">add bar\'s count</button></div>' , |
data: function () { |
return { |
fooCount: 0 |
} |
}, |
methods: { |
addBar: function () { |
// 触发事件 |
eventBus.$emit( 'addBar' ) |
} |
}, |
mounted: function () { |
eventBus.$on( 'addFoo' , function (num) { |
this .fooCount +=num |
}.bind( this )) |
// 这里必须将 this 绑定在组件实例上。如果不使用 bind , 也可以使用箭头函数。 |
} |
} |
// bar 组件 |
var bar = { |
template: '<div><p>the count of bar is {{barCount}}</p>' + |
'<button @click="addFoo">add foo\'s count</button></div>' , |
data: function () { |
return { |
barCount: 0 |
} |
}, |
methods: { |
addFoo: function () { |
// 触发事件,同时传递一个参数 |
eventBus.$emit( 'addFoo' , 2) |
} |
}, |
// 在 组件创建的钩子函数中 监听事件 |
mounted: function () { |
eventBus.$on( 'addBar' , function () { |
this .barCount++ |
}.bind( this )) |
} |
} |
var vm = new Vue({ |
el: '#app' , |
components: { |
foo, |
bar |
} |
}) |
</script> |
</body> |
</html> |
初级程序员
by: ahong977 发表于:2018-03-23 19:10:06 顶(0) | 踩(0) 回复
哎哟,不错哦。
回复评论