Skip to content

信息

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

¥This function will be removed in future version.

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

¥Vue 3.5 introduced the useTemplateRef API which can effectively replace the functionality of templateRef, therefore we recommend using the native approach.

templateRef

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

¥Shorthand for binding ref to template element.

用法

¥Usage

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

¥With 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 完全相同。

¥There is no need for this when using with <script setup> since all the variables will be exposed to the template. It will be exactly the same as ref.

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