VUE入门-父子组件之间的通信
By:Roy.LiuLast updated:2020-09-17
VUE中组件嵌套是很常见的场景,也就是父子组件嵌套。在这种情况下传递消息的注意处理方式如下:
父组件给子组件传递消息时,需要在 子组件定义 props:['属性名'] 来接收父组件的消息或者数据。
子组件传消息给父父组件时,通常采用 $emit('自定义事件名',变量1,变量2) 方式去触发父组件监听的事件。
在下面的例子中,注意如下几行代码:
sendToParent:function() {
this.$emit("toParent", "child给parent发送的消息")
}
...
<child child_prop='Message from parent' @toParent="getMsgFromChild"></child>特别是child 子组件申明这一项里面是重点, 父传子以及子传父相关的定义都在里面. 下面是完整的代码示例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
#child, #parent{
border:1px solid #ccc;
margin:10px 10px;
line-height: 30px;
}
</style>
<script src="vue.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/javascript">
var Child = {
template: `
<div id="child">
This is the child component. <br />
<font color=red>child prop: {{child_prop}}</font>
<button v-on:click="sendToParent">Send msg to parent</button>
</div>
`,
data:function(){
return {
}
},
props:['child_prop'],
methods:{
sendToParent:function() {
this.$emit("toParent", "child给parent发送的消息")
}
}
};
var Parent = {
template : `
<div id="parent">
This is the parent component. include child component. <br />
<font color=red>{{msg}}</font>
<child child_prop='Message from parent' @toParent="getMsgFromChild"></child>
</div>
`,
components:{
Child
},
data:function(){
return {
msg:"parent msg"
}
},
methods:{
sendToChild:function() {
},
getMsgFromChild:function(val){
this.msg=val;
}
}
};
new Vue({
el:"#app",
template:`
<div>
<parent></parent>
</div>
`,
data:function() {
return {
}
},
components:{
Parent
}
})
</script>
</body>
</html>From:一号门
Previous:VUE入门-平行兄弟组件之间的通信

COMMENTS