Vue3(单文件组件 + <script setup> + 组合式 API)组件实例常用内置属性、方法、函数

本文总结 Vue3 组件实例在模板中暴露的常用公共属性和方法,以及对应的 组合式 API 函数。

$data/$props/$options 属性在 组合式 API 下几乎用不到。
$el 不建议用。
$slots 表示父组件所传入插槽的一个对象,很少用,有兴趣可查看官方文档

$parent

模板中用 $parent 获取父组件实例,可访问父组件用 defineExpose() 显式暴露的绑定。

组合式 API 先在 setup 中用 getCurrentInstance() 获取到当前组件实例,再用 parent 属性访问父组件。getCurrentInstance().parent 除了能访问父组 defineExpose() 暴漏的绑定外,能访问父组件更多的属性和方法,多用于组件的开发,在应用开发中一般不建议用。

1
2
3
4
5
import { getCurrentInstance } from 'vue';

const parent = getCurrentInstance().parent; // 获取父组件的实例
parent.exposed // 访问父组件 defineExpose() 暴露的绑定
parent.refs // 父组件中的模板引用,在模板中用 $parent.$refs

$root

模板中通过 $root 变量访问根实例用 defineExpose() 显式暴露的绑定。
组合式 API 对应为 getCurrentInstance().root

$refs

组件实例的模板引用。
组合式 API 用 ref(null) 赋值给一个模板引用名同名的变量得到实例。

1
2
3
4
5
6
7
8
9
10
11
12
<script setup>
import { ref } from 'vue';

const inputRef = ref(); // 这样就可以用 inputRef 访问 MyComponent 显式暴露的绑定了。
</script>

<template>
<MyComponent ref="inputRef" />
<!-- 模板中用 $refs 访问模板实例 -->
{{ $refs.inputRef.xxx }}
</template>

$emit()

组合式 API 开发中,在模板中可以用 $emit() 触发事件,触发前需要先用 defineEmits() 声明事件。
setup 中用声明事件编译器宏 defineEmits() 返回的函数来触发事件。

1
2
3
4
5
6
7
8
9
10
11
12

<script setup>
const emt = defineEmits(['ev-1', 'ev-2'])
function myHandler() {
emt('ev-2')
}
</script>

<template>
<button @click="$emit('ev-1')"> click </button>
<button @click="myHandler"> click </button>
</template>

Vue3(单文件组件 + <script setup> + 组合式 API)组件实例常用内置属性、方法、函数

https://coderpan.com/front-end/vue-sfc-script-setup-component-instance.html

作者

CoderPan

发布于

2023-02-13

更新于

2024-05-08

许可协议

评论