ref是Vue中提供的一种可以快速获取目标元素(标签DOM对象、子组件)一种引用方式
1,语法
<!-- 给标签添加ref属性 -->
<input type="file" ref="header"/>
<!-- 给子组件添加ref属性 -->
<Child ref="child"/>
2,获取对象
methods: {
fn() {
// 获取文件域DOM对象
let f = this.$refs.file
// 获取子组件对象
let c = this.$refs.child
}
}
3,ref可以实现:父组件给子组件传递数据
<template>
<div class="ucenter-container">
<h2>用户中心</h2>
<UserDetail ref="udetail"/>
<button @click="showInfo">查看用户信息</button>
</div>
</template>
<script>
import UserDetail from '../components/UserDetail.vue'
export default {
data() {
return {
name: 'Mr.C',
age: 18
}
},
methods: {
showInfo() {
console.log(this.$refs.udetail)
// 可以通过ref对象,直接操作子组件中的数据
this.$refs.udetail.user.name = this.name
this.$refs.udetail.user.age = this.age
}
},
components: {
UserDetail
}
}
</script>
<style>
</style>
本文介绍了Vue中的ref特性,如何使用ref获取DOM元素和子组件实例,以及通过ref进行父子组件间的数据传递。通过实例演示了ref在实际开发中的应用和其重要性。
3382

被折叠的 条评论
为什么被折叠?



