- a.使用 $on(eventName) 监听事件
- b.使用 $emit(eventName) 触发事件
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Examples</title>
</head>
<body>
<div id="box">
父组件
<child @myevent2="handleEvent"></child>
</div>
<script src="http://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script type="text/javascript">
//子组件
Vue.component("child", {
template: `<div>
child组件
<button @click="payMoney()">click</button>
</div>`,
data() {
return {
childname: "子组件的状态"
}
},
methods: {
payMoney() {
//$emit()分发/触发 事件
this.$emit("myevent2", this.childname)
}
}
})
new Vue({
el: "#box",
methods: {
handleEvent(ev) {
console.log("父组件收到钱了", ev)
}
}
})
</script>
</body>
</html>
案例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Examples</title>
</head>
<body>
<div id="box">
<!-- <button @click="isShow=!isShow">click</button> -->
<navbar @myevent="handleEvent"></navbar><!--2-->
<sidebar v-show="isShow"></sidebar>
</div>
<script src="http://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script type="text/javascript">
//子组件
Vue.component("navbar", {
template: `<div>
navbar
<button @click="handleClick">navbar-button</button>
</div>`,
methods: {
handleClick() {
this.$emit("myevent")//1
}
}
})
Vue.component("sidebar", {
template: `<div style="background:yellow;width:200px;">
<ul>
<li>11111</li>
<li>11111</li>
<li>11111</li>
</ul>
</div>`
})
new Vue({
el: "#box",
data: {
isShow: false
},
methods: { //3
handleEvent() {
this.isShow = !this.isShow
}
},
})
</script>
</body>
</html>