vue中ref和$refs的用法

在日常开发中我们经常会用到ref,现在直接引用vue 官网对其简介
在这里插入图片描述
下面介绍几种ref常用案例:
1:获取dom元素

		<div @click="test" ref="test">点我吧</div>

还可以获取input 中输入的值,不用v-model 双向绑定,

<view @click="getTest"> 点我吧 </view>
		<view> 
		<input type="text" ref="inputs" style="background-color: #808080;">
		</view>
		methods: {
			getTest() {
				console.log(this.$refs.inputs.inputValue)
			}
		}

在这里插入图片描述

2:父组件可以拿到子组件data 中的值

子组件

<template>
	<div style="color:cyan;">我是child组件,谁调用我谁就是我的父组件</div>
</template>
<script>
	export default {
		data(){
			return{
				msg:'我是child自子组件中的msg'
			}
		}
	}
</script>

父组件(获取子组件data中的值)

<template>
	<view>
		<child ref="child"></child>
		<view @click="getTest"> 点我吧 </view>
	</view>
</template>
<script>
	 import child from '../compents/child.vue'
	export default {
		data() {
			return {
			}
		},
		components:{child},
		methods: {
			getTest() {
				console.log(this.$refs.child.msg)
			}
		}
	}
</script>

在这里插入图片描述
看上图我们可以在父组件中拿到子组件中的msg变量的值

3:父组件可以拿到子组件中的方法

子组件

<template>
	<view style="color:cyan;">我是child组件,谁调用我谁就是我的父组件</view>
</template>
<script>
	export default {
		data(){
			return{
				msg:'我是child自子组件中的msg'
			}
		},
		methods:{
			getref(){				
				return '父组件调用到我了'		
			}
		}
	}
</script>

父组件(调用子组件中的test方法)

<template>
	<view>
		<child ref="child"></child>
		<view @click="getTest"> 点我吧 </view>
	</view>
</template>
<script>
	import child from '../compents/child.vue'
	export default {
		data() {
			return {}
		},
		components: {
			child
		},
		methods: {
			getTest() {
				 console.log(this.$refs.child.getref())
			}
		}
	}
</script>

在这里插入图片描述
从上图看到我们可以在父组件中调用子组件中的方法

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值