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

vue中ref和$refs獲取元素dom、獲取子組件數(shù)據(jù)與方法調(diào)用示例

 更新時間:2024年07月17日 08:31:43   作者:小人參Y  
在Vue3中要獲取子組件的DOM節(jié)點,你可以使用ref來引用子組件,然后通過$refs來訪問子組件的DOM,下面這篇文章主要給大家介紹了關(guān)于vue中ref和$refs獲取元素dom、獲取子組件數(shù)據(jù)與方法調(diào)用的相關(guān)資料,需要的朋友可以參考下

作用

ref和$refs配合使用可以用于獲取DOM元素或組件實例

特點

查找范圍在當前組件內(nèi),更精確穩(wěn)定,范圍更小

使用

獲取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獲取,獲取到了即可拿到子組件的數(shù)據(jù)和方法

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">調(diào)用子組件方法</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數(shù)據(jù)是===', 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變量即已經(jīng)去獲取了對應(yīng)的dom或?qū)嵗?,相當于?zhí)行了this.$refs.xxx
let demo = ref()
let sonRef = ref()

const getDemo = () => {
    console.log('獲取到的demo的Dom數(shù)據(jù)是===', demo);
}
const getSonRef = () => {
    console.log('獲取到的子組件的實例是===', sonRef);
}
</script> -->

子組件代碼

<template>
    <div>子組件</div>
</template>
<script>
export default {

    data() {
        return {
            das: '我是子組件數(shù)據(jù)呀'
        }
    },
    methods: {
        fun() {
            console.log('我是子組件方法呀');
        }
    }
}
</script>

效果

總結(jié)  

到此這篇關(guān)于vue中ref和$refs獲取元素dom、獲取子組件數(shù)據(jù)與方法調(diào)用的文章就介紹到這了,更多相關(guān)vue ref和$refs獲取元素dom內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論