<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<title>组件通信$emit</title>
</head>
<body>
<div id="test">
</div>
<script>
Vue.component("ComponentA", {
template:`
<div>
我是组件A,count值为:{{count}}
<button @click="handleClick">你点击我增加</button>
</div>
`,
data() {
return {
count: 0
}
},
methods: {
handleClick() {
this.count++
this.$emit("cnAdd", this.count)
}
},
})
const app = new Vue({
el:"#test",
data:{
},
template:`
<div>
<ComponentA @cnAdd=handleCount></ComponentA>
</div>
`,
methods: {
handleCount(cn) {
console.log(cn);
}
},
})
</script>
</body>
</html>
效果截图: