Vue中的组件传值

默认情况下,components属性中的组件无法访问data中的数据和methods中的方法

1.父组件通过props属性来实现向子组件传值

  1. 定义子组件
var vm=new Vue({
	components:{
		coml:{
			template:'<p>{{parentmsg}}</p>'
		}
	}
})
  1. 定义父数据
var vm=new Vue({
	el:'#app',
	data:{
		msg:'a'
	}
})
  1. 将父组件数据引入到子组件
<div id="#app">
	<coml v-bind:parentmsg="msg">
	<!--v-bind:可以简写为:-->
	</coml>
</div>

v-bind:后面的名称就是数据的名称

  1. 定义子组件props
    新增一个props属性
var vm=new Vue({
	components:{
		coml:{
			props:['parentmsg']
		}
	}
})

与components中的data的区别
props是从父组件传递过来的,只能读取,不能修改父组件中的值
data是子组件私有的,可读可写

2.通过父组件向子组件传递方法来实现子组件向父组件传值传值

跟异步跨域访问类似,因为父组件的方法可以传递到子组件,子组件可以使用父组件的方法,所以可以传递一个参数给父组件进行处理

  1. 定义子组件
var vm=new Vue({
	components:{
		coml2:{
			template:'<input type="button" value="show" @click="myshow"/>'
		}
	}
})
  1. 定义父组件的方法
var vm=new Vue({
	el:'#app',
		methods:{
			show(data){
			//父组件对传回的data进行处理
			}
	}
})
  1. 将父组件的方法引入到子组件
<div id="app">
	<coml2 v-on:parentshow="show">
	<!--v-on:可以简写为@-->
	</coml2>
</div>
  1. 定义子组件的methods
var vm=new Vue({
	components:{
		coml:{
			methods:{
				myshow(){
					this.$emit('parentshow',需要传递的数据)
				}
			}
		}
	}
})

3.父组件通过ref获取子组件的数据

ref获取DOM元素和组件

vue提供了一个refs数组,存储了DOM元素的节点id
可以加在标签和组件上

  1. 在标签上加上属性ref
<p ref="a"></p>
  1. 获取DOM元素
this.$refs.a

具体使用

  1. 定义子组件
var vm=new Vue({
	components:{
		coml3:{
			template:'<p>子组件</p>',
			data:{
			msg:'子组件上的数据'
			}
		}
	}
})
  1. 在标签上加上ref属性
<coml3 ref="一个ID"></coml3>
  1. 父组件获取子组件中的数据
var vm=new Vue({
	el:'#app',
		methods:{
			show(){
				console.log(this.$refs.一个ID.msg)
			}
	}
})

4.父组件通过ref向子组件传递数据

  1. 定义子组件
var vm=new Vue({
	components:{
		coml4:{
			template:'<p>子组件</p>',
			data(){
				return{msg:'子组件上的数据'}
			},
			methods:{
				receive(data){
					this.msg=data
				}
			}
		}
	}
})
  1. 在标签上加上ref属性
<coml4 ref="一个ID"></coml4>
  1. 父组件调用子组件中的方法,实现传值
var vm=new Vue({
	el:'#app',
	data:{
		msg:'父组件的数据'
	},
		methods:{
			send(){
				console.log(this.$refs.一个ID.receive(this.msg))
			}
	}
})
  1. 调用父组件中的方法
<input type="button" @click="send"/>

总结:

对比传递数据
前两种方式比较麻烦,但是传递的数据可以不只是data中的数据。
第一种方式是由父组件向子组件传递
第二种方式是由子组件向父组件传递
第三种方式比较简单,只用一个id即可获取数据,就能向父组件传递子组件data中的数据
第四种方式比较简单,使用父组件调用子组件中的方法,实现向子组件传递父组件data中的数据
对比传递方法
第一种方式无法传递
第二种方式比较麻烦,只能由父组件传递方法给子组件调用
第三种方法无法传递
第四种方法比较简单,只能由子组件传递方法给父组件调用

posted @ 2020-02-11 14:42  程序员徐小白  阅读(75)  评论(0)    收藏  举报