Skip to content

Instantly share code, notes, and snippets.

@curder
Last active November 5, 2017 09:57
Show Gist options
  • Save curder/e4bf11768c52bef570e61ecc3d538bb5 to your computer and use it in GitHub Desktop.
Save curder/e4bf11768c52bef570e61ecc3d538bb5 to your computer and use it in GitHub Desktop.
VueJs组件通讯-兄弟组件使用$emit和$on通讯 视频参考:https://www.bilibili.com/video/av10323610/index_24.html?t=312#page=25
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>VueJs组件通讯-兄弟组件使用$emit和$on通讯</title>
<link href="https://cdn.bootcss.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div id="app">
<listener></listener>
<toggle-btn></toggle-btn>
</div>
<script src="https://cdn.bootcss.com/vue/2.4.4/vue.js"></script>
<script>
var bus = new Vue();
Vue.component('listener', {
template: `<h5>Sibling Component</h5>`,
mounted: function() {
bus.$on('everything-you-want',function(arg1, arg2){
console.log(arg1);
console.log(arg2);
});
}
});
Vue.component('toggle-btn', {
template: `
<a href="#"
class="btn btn-primary"
v-on:click.prevent="emitToggle"
v-text="title"></a>
`,
data: function() {
return {
title: 'Toggle Description',
}
},
methods: {
emitToggle() {
bus.$emit('everything-you-want','arg1','arg2');
}
}
});
var app = new Vue({
el: '#app'
});
</script>
</body>
</html>
@curder
Copy link
Author

curder commented Nov 5, 2017

  1. $emit 触发事件
  2. $on 监听并执行事件

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment