vue子组件传父组件
1、子组件created中this.$emit两个参数(要传给谁(自定义事件类型),要传的信息) || 微信小程序用this.traggerevent()
2、@定义一个方法,用于接收son传过来的信息
3、得到son传过来的信息,固定参数data
4、父元素data中定义数据用来接收使用来自son的信息
5、将得到的data值(这里的data是自定义方法中的data)传给data中定义好的数据中使用
6、使用son传来的信息
注:
$event可以用来传递默认参数
<!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传来的信息 -->
<!--getsonmsg($event,123) 可以用$event传递默认参数,这样会传递默认参数data和123-->
<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,data2) data为默认参数,data2为第二个参数123
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>

浙公网安备 33010602011771号