Vue组件-父组件向子组件传值

父组件向子组件传值

组件中可以用props来声明需要从父级接收的数据。
props和data、method平级,有两种方式:

1. 字符串数组方式,数组中的字符串就是传递时的名称

<div id="app">
		<!-- 第一步 使用bind绑定的方式 将父类的组件中的数据传给子组件 -->
		<parent :msg="msg"></parent>
	</div>
	
	<template id="temp">
		<h2>title{{msg}}</h2>
	</template>
	
	<script type="text/javascript">
		let parent=Vue.extend({
			template:'#temp',
			data(){
				return {
					msg:'默认'
				}
			},
			//第二步 使用props接收数据
			props:[
				"msg"
			]
		})
		var app=new Vue({
			el:"#app",
			data:{
				msg:'我是父组件msg'
			},
			components:{
				parent
			}
		})
	</script>

2. 对象方式,对象方式可以设置类型和默认值(一般开发用对象方式)

<div id="app">
		<parent :msg="msg"></parent>
	</div>
	
	<template id="temp">
		<h2>title{{msg}}</h2>
	</template>
	
	<script type="text/javascript">
		let parent=Vue.extend({
			template:'#temp',
			data(){
				return {
					msg:'默认'
				}
			},
			// props对象的方式给子组件传值
			props:{
				msg:{
					type:String,
					default:'我是默认值,父组件没有给我传数据'
				}
			}
		})
		var app=new Vue({
			el:"#app",
			data:{
				msg:'我是父组件msg'
			},
			components:{
				parent
			}
		})
	</script>

3. 父组件向子组件传递方法

<div id="app">
		<comp @compmethodmsg="alertMsg"></comp>
	</div>

	<template id="tmp">
		<button @click="handlerMethod">点我</button>
	</template>
	
	<script type="text/javascript">
		let comp=Vue.extend({
			template: "#tmp",
			methods:{
				handlerMethod(){
					//第一个参数表示要调用的方法
					//第二个参数表示要传递的参数
					this.$emit("compmethodmsg","调用")
				}
			}
		})
		let app=new Vue({
			el:"#app",
			data:{},
			methods:{
				alertMsg(msg){
					alert(msg);
				}
			},
			components:{
				comp
			}
		})
	</script>

4. 父组件调用子组件方法

$refs是ref一起用的。通过ref给某个子组件绑定一个特有的ID,然后用$refs.ID就可以访问到子组件了。

<div id="app">
		<button @click="countAdd">点我</button>
		<!-- 第一步 给子组件绑定ref -->
		<comp ref="myRef"></comp>
	</div>

	<template id="tmp">
		<h1>{{count}}</h1>
	</template>
	
	<script type="text/javascript">
		let comp=Vue.extend({
			template: "#tmp",
			data(){
				return {
					count:1
				}
			},
			methods:{
				addCount(){
					this.count++
				}
			}
		})
		let app=new Vue({
			el:"#app",
			methods:{
				countAdd(){
					//第二步 在父组件使用this.$refs.ID就能获得
					this.$refs.myRef.count++
				}
			},
			components:{
				comp
			}
		})
	</script>
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值