<!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>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id=‘app‘>
<father></father>
</div>
<template id="father">
<div>
{{fathermsg}}
<!-- 6、使用son传来的信息 -->
{{usesonmsg}}
<!-- 2、@定义一个方法,用于接收son传过来的信息 -->
<!-- 定义getsonmsg方法接收son传来的信息 -->
<son @send-msg-to-father=‘getsonmsg‘></son>
</div>
</template>
<template id="son">
<div>
{{sonmsg}}
</div>
</template>
<script>
Vue.component(‘father‘,{
template:‘#father‘,
data(){
return{
fathermsg:‘父元素信息‘,
usesonmsg:‘‘//4、定义数据用来接收使用来自son的信息
}
},
methods:{
// 3、得到son传过来的信息,固定参数data
getsonmsg(data){
console.log(data);// 打印结果 子元素信息
this.usesonmsg = data//5、将得到的data传给usesonmsg使用
}
}
})
Vue.component(‘son‘,{
template:‘#son‘,
data(){
return{
sonmsg:‘子元素信息‘
}
},
created(){
// 1、this.$emit两个参数(要传给谁,要传的信息)
// 把this.sonmsg传给fromson
this.$emit(‘send-msg-to-father‘,this.sonmsg)
}
})
const vm = new Vue({
el: ‘#app‘,
data: {
},
methods: {
},
})
</script>
</body>
</html>
原文:https://www.cnblogs.com/myqinyh/p/15306092.html