VUE入门-父子组件之间的通信

摘要: VUE中组件嵌套是很常见的场景,也就是父子组件嵌套。在这种情况下传递消息的注意处理方式如下

VUE中组件嵌套是很常见的场景,也就是父子组件嵌套。在这种情况下传递消息的注意处理方式如下:

  1. 父组件给子组件传递消息时,需要在 子组件定义 props:['属性名'] 来接收父组件的消息或者数据。

  2. 子组件传消息给父父组件时,通常采用 $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>


上一篇: VUE入门-平行兄弟组件之间的通信
下一篇: Vue axios与spring boot(mvc)通信交互的两种方式
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号