'ref' 属性的真正目的是什么? [英] what's the real purpose of 'ref' attribute?

查看:26
本文介绍了'ref' 属性的真正目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的对输入元素的ref"属性感到困惑.据我所知,我从来没有听说过,也找不到一些有意义的资料.代码在vue.js官方文档中.

I'm really confused with the "ref" attribute of the input element. I've never heard it based on my knowledge and can't find some meaningful materials about it.The code is in vue.js offical documents.

<currency-input v-model="price"></currency-input>

这是关于组件的代码:

Vue.component('currency-input', {
  template: `
    <span>
      $
      <input
        ref="input"
        v-bind:value="value"
        v-on:input="updateValue($event.target.value)">
    </span>
  `,
  props: ['value'],

ref 属性的值等于 input 是什么意思?

what's the meaning of the value of ref attribute that equals to input?

推荐答案

ref 属性的主要目的是使 DOM 元素成为可选的父 $refs 属性中的键.

The main purpose of the ref attribute is to make the DOM element selectable by being the key in the parent $refs attribute.

例如,您的输入元素在那里,使用 ref="input",将在其父级中公开其 DOM 节点(此处位于货币输入 this 中),如 <代码>this.$refs["input"](或this.$refs.input).

For example your input element there, with ref="input", would expose its DOM node in its parent (here inside currency-input this), as this.$refs["input"] (or this.$refs.input).

参见:https://vuejs.org/v2/api/#ref

它有几个用例,即使在可能的情况下不直接操作 DOM 通常会更好.例如,这里的一个合法用例是将焦点放在此输入上:为此,您可以在组件的方法中使用 this.$refs["input"].focus()...

It has several use cases, even if it would be often better when possible to not manipulate the DOM directly. For example, a legitimate use case here is to put focus on this input: for that you can use this.$refs["input"].focus() in a method of the component...

这篇关于'ref' 属性的真正目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆