vue组件通信 – 子传父
先决条件是子组件需要有一个主动事件来触发
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#app{
border:1px solid red;
padding:15px
}
.zx{
border:1px solid blue;
padding:15px
}
</style>
</head>
<body>
<div id="app">
父组件
<p>用来接受儿子送的东西:{{getchild}}</p>
<!-- <mydiv @来自子组件自定义的事件='父组件用来接受左边自定义事件所带的数据内容 方法'></mydiv> -->
<mydiv @inc='getchildfn'></mydiv>
</div>
<template id="mydiv">
<div class="zx">
我是子组件
<p>
<strong>把右边的内容送到父组件</strong>
{{msg}}
</p>
<button @click="song">把东西给父亲送过去</button>
</div>
</template>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
Vue.component('mydiv',{
template:"#mydiv",
data() {
return {
msg:"儿子张行给李元爸爸送点钱"
}
},
methods: {
song(){
// this.$emit('自定义的事件名','你要发出去的数据');
this.$emit('inc',this.msg);
}
},
created() {
this.song()
},
});
new Vue({
el:"#app",
data:{
getchild:""
},
methods: {
// 用来接受儿子信息
getchildfn(result){
this.getchild = result;
// 赋值给当前组件的DATA
console.log(result)
}
},
});
</script>
</body>
</html>