欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Vue獲取子組件實例對象ref屬性的方法推薦

 更新時間:2023年06月16日 09:28:29   作者:小吳吳吳呀  
在Vue中我們可以使用ref屬性來獲取子組件的實例對象,這個功能非常方便,這篇文章主要給大家介紹了關于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 文件夾內創(chuàng)建一個子組件。例如:Banner.vue 組件。

<template>
    <div>
        <h2>輪播圖</h2>
        <p>圖片數(shù)量:{{ 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 屬性,那么獲取到的就是這個組件的實例對象。并且可以通過這個對象,使用子組件內的數(shù)據和方法,或傳遞參數(shù)。

總結

到此這篇關于Vue獲取子組件實例對象ref屬性的文章就介紹到這了,更多相關Vue獲取子組件實例對象內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論