vue组件间消息传递的2种方式

1. 父组件向子组件传递
父组件向子组件传递信息也可以叫属性下行,在子组件上绑定一个自定义属性,属性值为父组件的模型数据,然后子组件通过props属性来接收传过来的数据。

<div id="app">
	<parentComponent></parentComponent>
</div>

<div id="parent">
	<childComponent :liNum="liNum"></childComponent>
</div>

<ul id="child">
	<li v-for="i in liNum">
		{{i}}
	</li>
</ul>

<script>
	var parentComponent = {
		template:"#parent",
		data:function(){
			return {
				liNum:10
			}
		},
		components:[childComponent]
	}
	var childComponent = {
		template:"#child",
		props:["liNum"]
	}
	new Vue({
		template:"#app",
		components:[parentComponent]
	})
</script>

2. 子组件向父组件传递
子组件向父组件传递信息也可以叫事件下行,通过在子组件上绑定一个自定义事件,事件函数为父组件定义,最后在子组件内定义一个事件来触发自定义事件(this.$emit(“自定义事件”,“传递的数据”))。

<div id="app">
	<parentComponent></parentComponent>
</div>

<div id="parent">
	<childComponent @childInfo="parentMe"></childComponent>
</div>

<div id="child">
	<button @click="info"></button>
</div>

<script>
	var parentComponent = {
		template:"parent",
		components:[childComponent],
		methods:{
			parentMe:function(d){
				alert(d);
			}
		}
	}
	var childComponent = {
		template:"child",
		data:function(){
			return {
				infoData:"hello world"
			}
		},
		methods:{
			info:function(){
				this.$emit("childInfo",this.infoData)
			}
		}
	}
	new Vue({
		template:"#app",
		components:[parentComponent]
	})
</script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值