zoukankan      html  css  js  c++  java
  • 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>
    

      

  • 相关阅读:
    VSCODE打开一个文件,另一个文件就关闭的问题的解决方法
    elementui的el-tree第一次加载无法展开和选中的问题
    Java线程知识:二、锁的简单使用
    “商家参数格式有误”应用切微信H5支付完美解决方案
    git 基础操作,公私钥认证/ssh公私钥登录
    Python数据分析之亚马逊股价
    Python分析6000家破产IT公司
    Python数据分析之股票数据
    Python数据分析之全球人口数据
    Vue 面试重点真题演练
  • 原文地址:https://www.cnblogs.com/linwenbin/p/13959944.html
Copyright © 2011-2022 走看看