子组件通过$emit方法用来触发事件
1.子组件定义一个方法,点击后会发出send
2.send被触发后,将触发parentsend,携带数据
3.自定义的事件,绑定父组件的方法handler()
4.调用父组件的方法
<!DOCTYPE html>
<html>
<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></title>
</head>
<body>
<div id="app">
<p>{{parent_msg}}</p>
<child @parentsend="handler"></child>
</div>
</body>
</html>
<script src="./js/vue.js"></script>
<script>
//全局组件(子组件)
Vue.component("child",{
template:`
<div>
<button @click=send>发送给父组件</button>
</div>
`,
data(){
return{
child_msg:"子组件的数据"
}
},
methods:{
send(){
//触发了parentsend,在parentsend携带child_msg
this.$emit("parentsend",this.child_msg)
}
},
})
//父组件
new Vue({
el:"#app",
data:{
parent_msg:""//父组件的data
},
methods:{
handler(msg){
this.parent_msg=msg;
}
}
})
</script>
运行后:
点击按钮后: