vue中ref和$refs获取元素dom、获取子组件数据与方法调用示例
作者:小人参Y
在Vue3中要获取子组件的DOM节点,你可以使用ref来引用子组件,然后通过$refs来访问子组件的DOM,下面这篇文章主要给大家介绍了关于vue中ref和$refs获取元素dom、获取子组件数据与方法调用的相关资料,需要的朋友可以参考下
作用
ref和$refs配合使用可以用于获取DOM元素或组件实例
特点
查找范围在当前组件内,更精确稳定,范围更小
使用
获取DOM
(1)在目标标签添加ref属性
<div ref="demo">测试测试</div>
(2)获取DOM
通过this.$refs.xxx获取,获取到了还可更改此元素样式等
const demoDom = this.$refs.demo;
获取子组件实例
(1)在子组件标签添加ref属性
<Son ref="sonRef"></Son>
(2)获取子组件实例
也是通过this.$refs.xxx获取,获取到了即可拿到子组件的数据和方法
const sonDom = this.$refs.sonRef;
完整例子
父组件代码(含vue3写法喔)
<template>
<div>
<div ref="demo">测试测试</div>
<h1 style="color: red;" :onclick="getDemo">点击获取demo</h1>
<h1 style="color: red;margin-top: 50px;" @click="getSonRef">点击获取子组件实例</h1>
<Son ref="sonRef"></Son>
<div v-if="sonData.das">
<p>{{ sonData.das }}</p>
<botton @click="sonData.fun">调用子组件方法</botton>
</div>
</div>
</template>
<script>
import Son from './son.vue'
export default {
components: {
Son
},
data() {
return {
sonData: {}
}
},
methods: {
getDemo() {
const demoDom = this.$refs.demo;
console.log('获取到的demo的Dom数据是===', demoDom);
},
getSonRef() {
const sonDom = this.$refs.sonRef;
this.sonData = sonDom;
console.log('获取到的子组件的实例是===', sonDom);
}
}
}
</script>
<!-- vue3的写法 -->
<!-- <script setup>
import Son from './son.vue'
import { ref } from 'vue'
// 声明同名的ref变量即已经去获取了对应的dom或实例,相当于执行了this.$refs.xxx
let demo = ref()
let sonRef = ref()
const getDemo = () => {
console.log('获取到的demo的Dom数据是===', demo);
}
const getSonRef = () => {
console.log('获取到的子组件的实例是===', sonRef);
}
</script> -->子组件代码
<template>
<div>子组件</div>
</template>
<script>
export default {
data() {
return {
das: '我是子组件数据呀'
}
},
methods: {
fun() {
console.log('我是子组件方法呀');
}
}
}
</script>效果

总结
到此这篇关于vue中ref和$refs获取元素dom、获取子组件数据与方法调用的文章就介绍到这了,更多相关vue ref和$refs获取元素dom内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
