【Vue.js】ref 逃生舱

139 阅读1分钟

概述

  • ref,全称 reference (引用), 是一种 Vue 的在数据驱动视图之外的额外解决方案

ref 的用途

  • 引用 DOM 元素, 引用组件实例

ref 的创建时机

  • 无论是元素引用,还是组件引用, ref都是只能在组件挂载完成后访问的
  • 所以,ref 只能在 mounted 之后访问

在 Vue 中,ref 是只读的

  • 当尝试修改 ref 的属性值时, 会有告警提示, 说明 ref 是只读的属性, 请不要尝试修改ref !

ref 的应用场景

  1. input 聚焦
<template>
  <input ref="inputRef" type="text" placeholder="请输入。。。" />
</template>

<script>
  import { defineComponent } from 'vue';

  export default defineComponent({
    name: 'MyInput',
    data() {
      return {};
    },
    mounted() {
      this.$refs.inputRef?.focus();
    }
  });

</script>
  1. 表单重置
<template>
  <form ref="formRef">
    <!-- ... -->
  </form>
</template>

<script>
  import { defineComponent } from 'vue';

	export default defineComponent({
    name: 'MyForm',
    data() {
      return {};
    },
    mounted() {
      this.$refs.formRef?.reset();
    }
  });
  
</script>
  1. 获取 DOM 元素上的特定属性 (自定义属性, 手动绑定事件处理函数也能解决)
  2. 兄弟组件之间调用方法 (回调机制)

ref 是否为响应式数据?

  • $refs 本身不是响应式的,请注意:

    1. 不要在模板中使用
    2. 不要在计算属性中使用
    3. 不要尝试修改ref的值,这样违背了模块的独立单一性

总结

  • ref 是一种应急方案(逃生舱), 请不要滥用
  • ref 违背了 MVVM 不能直接操作 DOM 的原则 (Vue 本质上也不能说是一个完全的 MVVM 框架)
  • 使用 props + emit 才是 Vue 里面最常见的解决方案