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.

为了完成对组件构成的研究,我们需要知道如何将子组件的数据传回父组件,接下来我们将探讨这一点。

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Vue3,$refs是一种用于访问DOM元素或组件实例的新API。它提供了一种简单的方式来获取组件或DOM元素的引用,类似于Vue2的$refs。不同于Vue2,Vue3的$refs可以是一个字符串或一个函数。当$refs是一个字符串时,在渲染时会将其关联到相应的元素或组件上,然后可以使用.value来访问它们。举个例子,在模板可以这样使用$refs: ```html <template> <div> <input ref="inputRef" /> <button @click="handleClick">Click me</button> </div> </template> <script> import { ref } from 'vue'; export default { setup() { const inputRef = ref(null); const handleClick = () => { inputRef.value.focus(); }; return { inputRef, handleClick, }; }, }; </script> ``` 在上面的例子,我们通过ref创建了一个名为inputRef的引用。然后在handleClick方法,我们可以使用inputRef.value来访问input元素并调用它的focus方法。这样就实现了通过$refs访问DOM元素的功能。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [vue3使用$refs](https://blog.csdn.net/weixin_52164116/article/details/129683079)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [vue3的refs用法](https://blog.csdn.net/XU441520/article/details/129553900)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Python私教

创业不易,请打赏支持我一点吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值