Vue3中$refs的使用

一、简介

有时候想访问$refs绑定的组件的属性或者方法,我们会使用$refs。但是Vue3不同于Vue2,在 Vue3的setup中我们是无法访问到this的,所以我们需要借助一个方法,那就是getCurrentInstance,该方法返回了当前的实力对象。但是要注意一下几点。

  • 不要把该函数当作是optionsApi中来获取 this 使用。
  • 该方法只在 setup、生命周期函数中有效,在方法中是无效

二、使用

<!-- 父组件 -->
<template>
    <div>
        <Child ref="child"></Child>
        <button @click="show">Show Child Message</button>
    </div>
</template>

<script>
import { getCurrentInstance, onMounted } from '@vue/runtime-core'
import Child from './Child.vue'
export default {
    components: {
        Child
    },
    setup() {
        let currentInstance = ''

        onMounted(() => {
            currentInstance = getCurrentInstance()
        })

        const show = () => {
            currentInstance.ctx.$refs.child.alertMessage()
        }

        return {
            show,
            currentInstance
        }
    }
}
</script>


<!-- 子组件 -->
<template>
    <div>
        <h1>{{ message }}</h1>
    </div>
</template>

<script>
import { ref } from "@vue/reactivity";


export default {
    setup() {
        const message = ref('我是子元素')

        const alertMessage = () => {
            alert(message.value)
        }

        return {
            message,
            alertMessage
        }
    },

}
</script>

Vue3中新增了 setup 语法糖的写法,下面也给出案例。setup 的语法糖的好处就是定义的数据和方法不用进行 return,也能够在模板中进行使用。

<!-- 父组件 -->
<template>
    <div>
        <Child ref="child"></Child>
        <button @click="show">Show Child Message</button>
    </div>
</template>


<script setup>

import { getCurrentInstance } from '@vue/runtime-core';
import Child from './Child.vue';

const currentInstance = getCurrentInstance()

function show() {
    currentInstance.ctx.$refs.child.alertMessage()
}

</script>

<!-- 子组件 -->
<template>
    <div>
        <h1>{{ message }}</h1>
    </div>
</template>

<script setup>
import { ref } from '@vue/reactivity';

let message = ref('我是子元素').value

const alertMessage = function () {
    alert(message)
}

defineExpose({
    message,
    alertMessage
})
</script>

注意⚠️,通过<script setup>语法糖的写法,其组件是默认关闭的,也就是说如果是通过$refs或者$parents来访问子组件中定义的值是拿不到的,必须通过defineExpose向外暴露你想获取的值才行。

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐