Vue父子组件通讯传值

Vue父子组件通讯传值

父组件往子组件传值

<body>
	<div id="App">
	    <!--可以采用v-bind动态传值-->
		<child :txt="msg"></child>
		<!--静态值(常量)-->
		<child txt="txt的属性值"></child>
		<!--采用默认值 前提是有设置-->
		<child></child>
	</div>
	<script>
		// 全局组件
		Vue.component("child",{
				template: "<p>{{txt}}</p>",
				props: {
					txt: {
						default: "组件自带的默认值"
					}
				}
			})
			
	    //props => Object || Array
		
		//组件传值
		let app = new Vue({
				el: "#App",
				data: {
					msg: "组件传值"
				}
			})
	</script>
</body>

子组件与父组件通信

方式1 采用中间件作为通讯中转站实现子组件往父级组件通讯传值的功能
<body>
	<div id="App">
		<em>电话次数: {{num}} </em>
	    <!--可以采用v-bind动态传值-->
		<child :txt="msg"></child>
		<!--静态值-->
		<child txt="txt的属性值"></child>
		<!--采用默认值 前提是有设置-->
		<child></child>
	</div>
	<script>

		let connectCar = new Vue();
		// 全局组件
		Vue.component("child",{
				template: "<p @click='callParent'>{{txt}}</p>",
				props: {
					txt: {
						default: "组件自带的默认值"
					}
				},
				methods: {
					callParent(){
						connectCar.$emit("call","Child发来信息了");
					}
				}
			})
		
		//组件传值
		let app = new Vue({
				el: "#App",
				data: {
					msg: "组件传值",
					num: 0
				},
				methods:{
					callChild(){
						connectCar.$on("call",msg => {
							console.log(msg);
							this.num ++;
						})
					}
				}
			})
		// 建立通信连接
		app.callChild();
	</script>
</body>
利用自定义事件实现子组件与父组件通讯
<body>
	<div id="App">
		<em>电话次数: {{num}} </em>
	    <!--可以采用v-bind动态传值-->
		<child :txt="msg" @call="callChild"></child>
		<!--静态值-->
		<child txt="txt的属性值" @call="callChild"></child>
		<!--采用默认值 前提是有设置-->
		<child @call="callChild"></child>
	</div>
	<script>

		let connectCar = new Vue();
		// 全局组件
		Vue.component("child",{
				template: "<p @click='callParent'>{{txt}}</p>",
				props: {
					txt: {
						default: "组件自带的默认值"
					}
				},
				methods: {
					callParent(){
						this.$emit("call","Child发来信息了");
					}
				}
			})
		
		//组件传值
		let app = new Vue({
				el: "#App",
				data: {
					msg: "组件传值",
					num: 0
				},
				methods:{
					callChild(msg){
						console.log(msg);
						this.num ++;
					}
				}
			})
	</script>
</body>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值