methods:{
recvMsg:function(msg){
//参数msg就是子组件通过事件出来的数据
}
}
<child-component @myEvent="recvMsg"></child-component>
事件名,值
this.$emit('myEvent',myPhone)
//触发一个叫做myEvent的事件,同时把第二个参数数据传递给事件对应的处理函数
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>组件间通信子传父</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="container">
<p>{{msg}}</p>
<parent-component></parent-component>
</div>
<script>
//通过事件的方式传递
// 绑定 -- 触发
Vue.component("parent-component",{
data:function(){
return {
sonMsg:""
}
},
methods:{
//msg参数要拿子传递的值
recvMsg:function(msg){
console.log("父组件接收到子组件的数据"+msg);
this.sonMsg = msg;
}
},
template:`
<div>
<h1>这是父组件</h1>
<p>子组件传来的数据为:{{sonMsg}}</p>
<hr/>
<child-component @customEvent="recvMsg"></child-component>
</div>
`
})
Vue.component("child-component",{
methods:{
sendMsg:function(){
//来触发绑定给子组件的自定义方法
//this.$emit("customEvent");第一个参数触发
//this.$emit("customEvent");第二个参数传值
this.$emit("customEvent","哈哈哈哈");
},
},
template:`
<div>
<h1>这是子组件</h1>
<button @click="sendMsg">senToFather</button>
</div>
`
})
new Vue({
el:"#container",
data:{
msg:"Hello VueJs"
}
})
</script>
</body>
</html>
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>子与父之间的通信</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="container">
<p>{{msg}}</p>
<parent-component></parent-component>
</div>
<script>
//创建父组件
Vue.component("parent-component",{
//data属性
data:function(){
return{
sonMsg:""
}
},
methods:{
recvMsg:function(msg){
this.sonMsg = msg
}
},
template:`
<div>
<h1>父组件</h1>
<h4>子组件传递的数据:{{sonMsg}}</h4>
<child-component @customEvent="recvMsg"></child-component>
</div>
`
})
//创建子组件
Vue.component("child-component",{
data:function(){
return {
myInput:""
}
},
methods:{
sendMsg:function(){
this.$emit("customEvent",this.myInput);
}
},
template:`
<div>
<h1>子组件</h1>
<input type="text" v-model="myInput"/>
<button @click="sendMsg">发送</button>
</div>
`
})
new Vue({
el:"#container",
data:{
msg:"Hello VueJs"
}
})
</script>
</body>
</html>
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有