2020-3-18 前端達(dá)人
var newvue = new Vue()
觸發(fā)事件
newvue.$emit('自定義事件名', 參數(shù))
監(jiān)聽(tīng)事件
newvue.on('自定義事件名', 觸發(fā)方法名)
銷(xiāo)毀事件
newvue.off('自定義事件名')
案例
放在html頁(yè)面上即可顯示,注意要引入vue
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="app">
<div>父組件</div>
<div>
<button @click='handle'>銷(xiāo)毀事件</button>
</div>
<test-tom></test-tom>
<test-jerry></test-jerry>
</div>
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript">
/*
兄弟組件之間數(shù)據(jù)傳遞
*/
// 提供事件中心
var hub = new Vue();
Vue.component('test-tom', {
data: function(){
return {
num: 0
}
},
template: `
<div>
<div>TOM:{{num}}</div>
<div>
<button @click='handle'>點(diǎn)擊</button>
</div>
</div>
`,
methods: {
handle: function(){
hub.$emit('jerry-event', 2);
}
},
mounted: function() {
// 監(jiān)聽(tīng)事件
hub.$on('tom-event', (val) => {
this.num += val;
});
}
});
Vue.component('test-jerry', {
data: function(){
return {
num: 0
}
},
template: `
<div>
<div>JERRY:{{num}}</div>
<div>
<button @click='handle'>點(diǎn)擊</button>
</div>
</div>
`,
methods: {
handle: function(){
// 觸發(fā)兄弟組件的事件
hub.$emit('tom-event', 1);
}
},
mounted: function() {
// 監(jiān)聽(tīng)事件
hub.$on('jerry-event', (val) => {
this.num += val;
});
}
});
var vm = new Vue({
el: '#app',
data: {
},
methods: {
handle: function(){
hub.$off('tom-event');
hub.$off('jerry-event');
}
}
});
</script>
</body>
</html>
————————————————
版權(quán)聲明:本文為CSDN博主「溫柔的堅(jiān)持」的原創(chuàng)文章,遵循 CC 4.0 BY-SA 版權(quán)協(xié)議,轉(zhuǎn)載請(qǐng)附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/weixin_43745003/article/details/104919633
藍(lán)藍(lán)設(shè)計(jì)的小編 http://www.ty-hotel.net