'ref'属性的真正目的是什么?

edi*_*xue 57 vue.js

我真的很困惑输入元素的"ref"属性.我从来没有根据我的知识听到它,也找不到一些有意义的材料.代码在vue.js官方文档中.

<currency-input v-model="price"></currency-input>
Run Code Online (Sandbox Code Playgroud)

这是关于组件的代码:

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

ref属性值等于输入的含义是什么?

Cob*_*way 67

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

例如,你的输入元素with ref="input",会在其父节点(这里是货币输入内this)中公开它的DOM节点,如this.$refs["input"](或this.$refs.input).

请参阅:https://vuejs.org/v2/api/#ref

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

  • 或者更简单的`this.$refs.input.focus()` (3认同)

Mic*_*ulu 20

  • $refs 用于选择/定位HTML元素
  • $refs就像document.querySelector('.el')在vanilla JS或$('.el')jQuery中一样
  • $refs 可以在VueJS实例的内部或外部访问.
  • $refs与数据属性不同,它们不是反应性的.

因此,建议$refs在您希望侦听/操作/更改未连接/控制任何Vue实例属性的元素的值时使用,以避免冲突.