Vue中$refs与$emit的区别及使用场景实例

转自:https://blog.csdn.net/CiCiCi12/article/details/107030215/

refs1)过refs访问或修改子组件的数据,又可以访问子组件方法。
场景1:父组件发生某个事件,在事件执行的方法中,需要访问或者更改子组件数据属性或调用子组件方法。
此时可以使用c h i l d r e n 和 children和children和refs.但是c h i l d r e n 不 常 用 , 通 常 使 用 children不常用,通常使用children使用refs。

	<div id="app">
		<cpn ref="cpnRef"></cpn>
		<button @click="btnclick">按钮</button>
	</div>
	<template id="tem">
		<div>
			<p>我是子组件</p>
			{{message}}				
		</div>
	</template>
	<script src="../js/vue.js"></script>
	<script>
		let app = new Vue({
			el:'#app',
			data:{
				name:'xixixi'
			},
			methods:{
				btnclick(){
					console.log("这是父组件方法");
					//this.$children[0].cpnclick();
					this.$refs.cpnRef.cpnclick();
					//console.log(this.$refs.cpnRef.message);
					this.$refs.cpnRef.message = 'info';
				}
			},
			components:{
				cpn:{
					template:'#tem',
					data(){
						return{
							message:'mess'
						}		
					},
					methods:{
						cpnclick(){
							console.log("这是子组件方法");		
						}
					}
				}
			}
		});
	</script>

  

.emit12)过emit父组件只能获取子组件传递过来的数据,不能修改此数据,也不能访问子组件其他属性以及方法。

场景2:父组件发生某个事件,在事件执行的方法中,需要访问或者更改子组件数据属性或调用子组件方法。

	<div id="app">
		<cpn @cpnclick="parentclick"></cpn>		
	</div>
	<template id="tem">
		<div>
			<p>我是子组件</p>	
			<button @click="btnclick">按钮</button>		
		</div>
	</template>
	<script src="../js/vue.js"></script>
	<script>
		let app = new Vue({
			el:'#app',
			data:{
				name:'xixixi'
			},
			methods:{
				parentclick(value){
					console.log("从子组件传递过来的值为:"+value);			
				}
			},
			components:{
				cpn:{
					template:'#tem',				
					methods:{
						btnclick(){					
							let value = "hello world";	
							console.log("将要传递给父组件的值为:"+value);	
							this.$emit('cpnclick',value);
						}
					}
				}
			}
		});
	</script>

  

原文地址:https://www.cnblogs.com/linwenbin/p/13959944.html