Vue获取子组件实例对象 ref 属性

在 Vue 中推荐使用 ref 属性获取 DOM 元素,这种方式可以提高性能。

如果将 ref 属性使用在组件上,那么返回的就是这个组件的实例对象。

使用方式:`<p ref="xxx">` 或 `<Banner ref="xxx">` 。

获取方式:this.$refs.xxx

1.原生 JS 获取 DOM 元素【不推荐】:

<template>
    <div>
        <h2>主页</h2>
        <p id="title">{
   
   { msg }}</p>
        <button @click="getDOM">点击获取DOM元素</button>
    </div>
</template>

<script>
export default {
    name: 'Home',
    data() {
        return {
            msg: "哇哈哈哈!"
        }
    },
    methods: {
        getDOM() {
            // 通过原生 JS 获取 DOM 元素
            console.log(document.getElementById("title"));
        }
    }
}
</script>

2. 通过 ref 属性获取 DOM 元素【推荐】:

<template>
    <div>
        <h2>主页</h2>
        <p ref="title">{
   
   { msg }}</p>
        <button @click="getDOM">点击获取DOM元素</button>
    </div>
</template>

<script>
export default {
    name: 'Home',
    data() {
        return {
            msg: "哇哈哈哈!"
        }
    },
    methods: {
        getDOM() {
            // 通过 ref 属性获取 DOM 元素
            console.log(this.$refs.title);
            console.log(this);
        }
    }
}
</script>

:ref 属性就是 id 的替代者,会将绑定 ref 属性的元素添加到 Vue 实例对象上,可以通过 $refs 属性获取这个 DOM 元素。

 


 获取子组件实例对象:

首先需要在 components 文件夹内创建一个子组件。例如:Banner.vue 组件。

<template>
    <div>
        <h2>轮播图</h2>
        <p>图片数量:{
   
   { num }}</p>
    </div>
</template>

<script>
export default {
    name: "Banner",
    data() {
        return {
            num: 5
        }
    }
}
</script>


然后在 Home.vue 页面引入 banner.vue 组件。并给组件绑定 ref 属性。

<template>
    <div>
        <h2>主页</h2>
        <p ref="title">{
   
   { msg }}</p>
        <button @click="getDOM">点击获取DOM元素</button>
        <Banner ref="ban"></Banner>
    </div>
</template>

<script>
import Banner from "../components/Banner";
export default {
    name: 'Home',
    components: { Banner },
    data() {
        return {
            msg: "哇哈哈哈!"
        }
    },
    methods: {
        getDOM() {
            // 通过 ref 属性获取子组件实例对象
            console.log(this.$refs.ban);
            console.log(this.$refs.ban.num);
        }
    }
}
</script>

:如果在组件上绑定 ref 属性,那么获取到的就是这个组件的实例对象。并且可以通过这个对象,使用子组件内的数据和方法,或传递参数。

原创作者:吴小糖

创作时间:2023.3.24

猜你喜欢

转载自blog.csdn.net/xiaowude_boke/article/details/129743205