父子组件通信(props 与 $emit)——Vue 学习笔记(十)

父组件传递数据给子组件

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>父组件传值给子组件</title>
		<script type="text/javascript" src="../js/vue.js"></script>
	</head>
	<body>
		<div id="app">
			<father v-bind:fatherinfo="vueinfo"></father>
		</div>
		<script>
			Vue.component('father', {
				props: ['fatherinfo'],
				components: {
					'inner': {
						props: ['innerinfo'],
						template: '<p>I am inner,info:{{ innerinfo }}</p>'
					}
				},
				template: `
				  <div>
				    <p>I am father,info:{{ fatherinfo }}</p>
				    <inner v-bind:innerinfo="fatherinfo"></inner>
				  </div>
				`
			})
			let vm = new Vue({
				el: '#app',
				data: {
					vueinfo: 'I am vue info'
				}
			})
		</script>
	</body>
</html>

效果:


在上面的例子中,父组件 father 组件将从 Vue 实例获取的 vueinfo 传递给了子组件 inner。

fater 组件首先通过 v-bind 指令获取到 Vue 实例的 vueinfo,并将其赋值给自定义属性 fatherinfo,然后再通过 v-bind 指令将该值赋值给子组件 inner 的自定义属性 innerinfo,从而实现了父组件传值给子组件。

子组件 v-bind 的值查询范围仅限于直接父组件,在上面的例子中:

inner 组件 v-bind 的值查询范围仅限于父组件 father 组件,它不能通过 v-bind 指令直接访问到 Vue 实例的数据。

如果 inner 组件内部又定义了子组件,那这个新定义的子组件 v-bind 指令只能查询到 inner 组件的数据,不能直接查询到 father 组件的数据。


子组件传递数据给父组件

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>子组件传值给父组件</title>
		<script src="../js/vue.js"></script>
	</head>
	<body>
		<div id="app">
			<father v-bind:fatherinfo="info"></father>
		</div>
		<script>
			Vue.component('father', {
				props: ['fatherinfo'],
				components: {
					'inner': {
						template: `
						<div>
						  <button v-on:click="$emit('changeinfo', 'innerinfo')">change</button>
						  <p>点击按钮之后,fatherinfo 的值将变为 innerinfo</p>
						</div>
						`
					}
				},
				methods: {
					change: function(e) {
						this.fatherinfo = e;
					}
				},
				template: `
				  <div>
				    <p>fatherinfo: {{ fatherinfo }}</p>
				    <inner v-on:changeinfo="change"></inner>
				  </div>
				`
			});
			let vm = new Vue({
				el: '#app',
				data: {
					info: 'I am vue info'
				}
			})
		</script>

	</body>
</html>

效果:


在上面的例子中,子组件 inner 通过 $emit 改变了 父组件 father 组件的自定义属性 fatherinfo 的值,这种操作会让 Vue 在浏览器的控制台中发出警告 QAQ。

$emit 方法会触发当前实例上事件,此方法第一个参数为事件名,第二个参数是一个参数数组,会传给监听器回调,在上面的例子中:

子组件 inner 通过 $emit 方法触发 changeinfo 事件,这个事件被监听到后又触发了 change 函数,在 change 里面,$emit 方法的第二个参数会被传入,从而修改父组件 father 组件的自定义属性 fatherinfo 的值。

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值