Vue中ref的用法

本文介绍了Vue.js中ref属性的三种常见用法:1) 在普通元素上,ref用于获取DOM元素;2) 在子组件上,ref获取组件实例,允许调用组件方法;3) 如何通过ref调用组件内的方法。示例代码展示了如何在事件处理函数中使用this.$refs来操作元素或组件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        1、ref 加在普通的元素上,用this.$refs.(ref值) 获取到的是dom元素

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<div id="app">
			<p @click="handClick" ref="pp" id="p">你好web2208</p>
		</div>
		
		<script src="vue.js"></script>
		<script type="text/javascript">
			const vm = new Vue({
				el:"#app",
				data(){
					return{	}
				},
				methods:{
					handClick(){
						console.log(document.getElementById("p"));
						console.log(this.$refs.pp);
						console.log(document.getElementById("p").innerHTML);
						console.log(this.$refs.pp.innerHTML);
					}
				}
			})
		</script>
	</body>
</html>

 

  2、ref 加在子组件上,用this.$refs.(ref值) 获取到的是组件实例,可以使用组件的所有方法。在使用方法的时候直接this.$refs.(ref值).方法() 就可以使用了。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<!-- ref 加在子组件上,用this.$refs.(ref值) 获取到的是组件实例,可以使用组件的所有方法。在使用方法的时候直接this.$refs.(ref值).方法() 就可以使用了。 -->
	</head>
	<body>
		<div id="app">
			<counter ref="one" @change="handClick"></counter>
			<counter ref="two" @change="handClick"></counter>
			<h2>{{total}}</h2>
		</div>

		<script src="vue.js"></script>
		<script type="text/javascript">
			Vue.component("counter", {
				template: `<div @click="handClick">{{number}}</div>`,
				data() {
					return {
						number: 0,
					}
				},
				methods: {
					handClick() {
						this.number++
						this.$emit("change")
					}
				}
			})

			const vm = new Vue({
				el: "#app",
				data() {
					return {
						total: 0
					}
				},
				methods: {
					handClick() {
						this.total = this.$refs.one.number + this.$refs.two.number
						console.log(this.$refs);   //这里的this.$refs指的是one、two两个组件实例
					}
				}
			})
		</script>
	</body>
</html>

最后代码的效果就是x、y各点一次加1,最后实现x+y=z的效果


        3、ref可以调用组件中的方法

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
	</head>
	<body>
		<div id="app">
			<helloworld ref="hello"></helloworld>
			<button @click="getHello">获取helloWorld组件中的值</button>
		</div>
		
		<script src="vue.js"></script>
		<script type="text/javascript">
			Vue.component("helloworld",{
				template:`<div></div>`,
				data(){
					return{
						number:0
					}
				},
				methods:{
					handClick(){
						console.log("被调用了");
					}
				}
			})
			
			const vm = new Vue({
				el:"#app",
				data(){
					return{}
				},
				methods:{
					getHello(){
						this.$refs.hello.handClick()	//调用了组件实例中的handClick方法
						console.log(this.$refs.hello);	//调用了组件实例
						console.log(this.$refs.hello.number);	//得到了组件实例中的number
					}
				}
			})
		</script>
	</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值