vue ref和$refs 获取元素dom、获取子组件数据与方法

前端 0
作用

        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.xxxlet 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>

        效果

也许您对下面的内容还感兴趣: