跳到主要内容

信息

此函数将在未来版本中移除。

Vue 3.5 引入了 useTemplateRef API,它可以有效地替代 templateRef 的功能,因此我们建议使用原生方法。

templateRef

分类
导出大小
283 B
上次更改
3 个月前

将 ref 绑定到模板元素的简写。

用法

vue
<script lang="ts">
import { 
templateRef
} from '@vueuse/core'
export default {
setup
() {
const
target
=
templateRef
('target')
// no need to return the `target`, it will bind to the ref magically }, } </script> <template> <
div
ref
="
target
" />
</template>

使用 JSX/TSX

tsx
import { templateRef } from '@vueuse/core'

export default {
  setup() {
    const target = templateRef<HTMLElement | null>('target', null)

    // use string ref
    return () => <div ref="target"></div>
  },
}

<script setup>

当与 <script setup> 一起使用时,无需此功能,因为所有变量都将暴露给模板。它将与 ref 完全相同。

vue
<script setup lang="ts">
import { 
ref
} from 'vue'
const
target
=
ref
<HTMLElement | null>(null)
</script> <template> <
div
ref
="
target
" />
</template>

类型声明

ts
/**
 * @deprecated Use Vue's built-in `useTemplateRef` instead.
 *
 * Shorthand for binding ref to template element.
 *
 * @see https://vueuse.org.cn/templateRef
 * @param key
 * @param initialValue
 *
 * @__NO_SIDE_EFFECTS__
 */
export declare function 
templateRef
<
T
extends HTMLElement | SVGElement |
Component
| null,
Keys
extends string = string,
>(
key
:
Keys
,
initialValue
?:
T
| null):
Readonly
<
Ref
<
T
>>

来源

源代码文档

贡献者

Anthony Fu
Anthony Fu
SerKo
IlyaL
zhiyuanzmj
Hollis Wu
likeswinds
Alex Kozack
zhong666

更新日志

v13.6.0
d32f8 - refactor: 为所有纯函数添加 @__NO_SIDE_EFFECTS__ 注释 (#4907)
0271e - feat: 标记 templateRef 为已废弃 (#4894)
0a9ed - feat!: 放弃对 Vue 2 的支持,优化打包并清理 (#4349)
v11.0.2
acce3 - feat: 支持通过泛型参数指定允许的键 (#4162)

根据 MIT 许可证发布。