16 Vue3中的refs引用
概述
In Vue, refs are references to DOM elements or other component instances that have been mounted to the DOM.
在 Vue 中,Refs 是对 DOM 元素或已安装到 DOM 的其他组件实例的引用。
One of the major use cases for refs is direct DOM manipulation and integration with DOM-based libraries (that usually take a DOM node they should mount to), such as an animation library.
refs 的主要用途之一是直接操作 DOM 并与基于 DOM 的库集成(这些库通常需要挂载到一个 DOM 节点),例如动画库。
We define refs by using the syntax ref=“name” on a native element or child component in the template. In the following example, we will add a reference to the input element under the name theInput:
我们可以在模板中的原生元素或子组件上使用 ref=“name” 语法来定义引用。在下面的示例中,我们将为输入元素添加一个引用,名称为 theInput:
<template>
<div id="app">
<input ref="theInput" />
</div>
</template>
Refs can be accessed from the Vue component instance through this. r e f s [ r e f N a m e ] . S o , i n t h e p r e c e d i n g e x a m p l e , w h e r e w e h a d a r e f d e f i n e d a s r e f = " t h e I n p u t " , i t c a n b e a c c e s s e d t h r o u g h t h i s . refs[refName]. So, in the preceding example, where we had a ref defined as ref="theInput", it can be accessed through this. refs[refName].So,intheprecedingexample,wherewehadarefdefinedasref="theInput",itcanbeaccessedthroughthis.refs.theInput.
可以通过 this. r e f s [ r e f N a m e ] 访问 V u e 组件实例中的 r e f 。因此,在前面的示例中,我们将 r e f 定义为 r e f = " t h e I n p u t " ,可以通过 t h i s . refs[refName] 访问 Vue 组件实例中的 ref。因此,在前面的示例中,我们将 ref 定义为 ref="theInput",可以通过 this. refs[refName]访问Vue组件实例中的ref。因此,在前面的示例中,我们将ref定义为ref="theInput",可以通过this.refs.theInput 进行访问。
Now let’s programmatically focus on the input field when clicking the Focus Input button, as follows:
现在,让我们通过编程,在单击 "聚焦输入 "按钮时聚焦输入框,如下所示:
<template>
<div id="app">
<input ref="theInput" />
<button @click="focus()">Focus Input</button>
</div>
</template>
<script>
export default {
methods: {
focus() {
this.$refs.theInput.focus()
}
}
}
</script>
Note here that we can only access
r
e
f
s
o
n
c
e
t
h
e
c
o
m
p
o
n
e
n
t
i
s
m
o
u
n
t
e
d
t
o
t
h
e
D
O
M
.
H
e
n
c
e
t
h
i
s
.
refs once the component is mounted to the DOM. Hence this.
refsoncethecomponentismountedtotheDOM.Hencethis.refs.theInput in our example is only available in the mounted() life cycle hook. Also, if you use <script setup>
, there is no $refs available since there is no this and setup runs before the component instance is created. Hence to use DOM references with <script setup>
or the setup hook, we use the ref() function from the Composition API instead.
请注意,只有当组件挂载到 DOM 时,我们才能访问
r
e
f
s
。因此,我们示例中的
t
h
i
s
.
refs。因此,我们示例中的 this.
refs。因此,我们示例中的this.refs.theInput 只能在 mounted() 生命周期钩子中使用。此外,如果使用 <script setup>
,由于在创建组件实例之前没有 this 和 setup,因此没有 $refs 可用。因此,要在 <script setup>
或设置钩子中使用 DOM 引用,我们可以使用 Composition API 中的 ref() 函数。
We have learned how to use $refs to access the DOM elements from the component. When you need select a DOM node directly, we recommend you use a ref instead of using the DOM API (querySelector/querySelectorAll).
我们已经学会了如何使用 $refs 访问组件中的 DOM 元素。当您需要直接选择 DOM 节点时,我们建议您使用 ref 而不是使用 DOM API(querySelector/querySelectorAll)。
In the following exercise, we will learn how the Countable library helps increase interactivity in a project.
在下面的练习中,我们将学习 Countable 库如何帮助提高项目的交互性。
练习:使用Countable.js库
Countable is a library that, given an element (usually an HTML textarea or input), will add live counts of paragraphs, words, and characters. Live metrics on the text being captured can be quite useful to increase interactivity in a project where editing text is a core concern.
Countable 是一个库,当给定一个元素(通常是 HTML 文本区域或输入)时,它将添加段落、单词和字符的实时计数。在以编辑文本为核心关注点的项目中,对所捕获文本的实时度量对于提高交互性非常有用。
Create a new src/components/TextEditorWithCount.vue component with a textarea that we will have a ref to:
创建一个新的 src/components/TextEditorWithCount.vue 组件,其中包含一个文本区,我们将为其创建一个引用:
<template>
<div>
<textarea
ref="textArea"
cols="50"
rows="7"
>
</textarea>
</div>
</template>
Next, we will import and render the component in src/App.vue:
接下来,我们将在 src/App.vue 中导入并渲染该组件:
<template>
<div id="app">
<TextEditorWithCount/>
</div>
</template>
<script>
import TextEditorWithCount from './components/TextEditorWithCount.vue'
export default {
components: {
TextEditorWithCount
}
}
</script>
线安装Countable:
yarn add countable
# 或者
npm add countable
We now need to integrate Countable. We will import it and initialize it with this.$refs.textArea. We will also store the counts on the instance as this.count:
现在我们需要集成 Countable。我们将导入 Countable 并用 this.$refs.textArea 进行初始化。我们还将以 this.count 的形式在实例中存储计数:
<script>
import * as Countable from 'countable'
export default {
mounted() {
Countable.on(this.$refs.textArea, (count) => {
this.count = count
})
},
data() {
return {
count: null
}
}
}
</script>
With a small update to template, we can display the counts we care about:
只需对模板稍作更新,我们就能显示我们关心的计数:
<template>
<div>
<!--段落-->
<textarea
ref="textArea"
cols="50"
rows="7"
>
</textarea>
<!--段落计数-->
<ul v-if="count">
<li>Paragraphs: {{ count.paragraphs }}</li>
<li>Sentences: {{ count.sentences }}</li>
<li>Words: {{ count.words }}</li>
</ul>
</div>
</template>
One last thing we need to do is remove the Countable event listener when the component is unmounted:
我们需要做的最后一件事是在组件卸载时移除 Countable 事件监听器:
<script>
import * as Countable from 'countable'
export default {
/**
* 挂载方法,监听文本域
*/
mounted() {
Countable.on(this.$refs.textArea, (count) => {
this.count = count
})
},
/**
* 卸载之前,移除监听
*/
beforeUnmount() {
Countable.off(this.$refs.textArea)
},
data() {
return {
count: null
}
}
}
</script>
This integration of a JavaScript/DOM library inside a Vue app is a key application of Vue refs. Refs allow us to pick from the existing ecosystem of libraries and wrap or integrate them into a component.
在 Vue 应用程序中集成 JavaScript/DOM 库是 Vue Refs 的一项重要应用。通过 Refs,我们可以从现有的库生态系统中挑选库,并将它们封装或集成到一个组件中。
Vue refs are useful for integrating DOM libraries or for accessing DOM APIs directly.
Vue refs 可用于集成 DOM 库或直接访问 DOM API。
To round off our examination of component composition, we need to know how to pass data from child components back to their parents, which we will explore next.
为了完成对组件构成的研究,我们需要知道如何将子组件的数据传回父组件,接下来我们将探讨这一点。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!