Vue gets subcomponent instance object ref attribute

In Vue, it is recommended to use the ref attribute to obtain DOM elements, which can improve performance.

If the ref attribute is used on a component, then the instance object of this component is returned.

Usage: `<p ref="xxx">` or `<Banner ref="xxx">`.

Obtaining method: this.$refs.xxx

1. Get DOM elements from native JS [not recommended]:

<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. Obtain the DOM element through the ref attribute [recommended]:

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

Note : The ref attribute is a substitute for id, and the element bound to the ref attribute will be added to the Vue instance object, and the DOM element can be obtained through the $refs attribute.

 

 


 Get the subcomponent instance object:

First you need to create a subcomponent inside the components folder. For example: Banner.vue component.

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

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


Then introduce the banner.vue component in the Home.vue page. And bind the ref attribute to the component.

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

Note : If you bind the ref attribute on the component, then what you get is the instance object of this component. And through this object, use the data and methods in the subcomponent, or pass parameters.

 

Original author: Wu Xiaotang

Creation time: 2023.3.24

Guess you like

Origin blog.csdn.net/xiaowude_boke/article/details/129743205