【Vue.js】Composition API - ref()

151 阅读1分钟

概述:

  • ref 函数接收一个参数, 然后返回一个"响应式", "可更改"的 ref 对象
import { ref } from 'vue';

const inputRef = ref('');

使用:

外界通过 ref.value 的属性访问 ref 对象的内部值

访问:

  1. 在脚本(<script> 或者 <script setup>)中,访问 ref 的值需要使用 ref.value进行访问:
import { ref } from 'vue';

const inputRef = ref('');

const getInputRefValue = () => {
  return inputRef.value;
}
  1. 在视图 (<template>)中,ref 直接传递即可。模板可以将 ref 对象自动解包成真实渲染的值:
<script>
  import { defineComponent, ref } from 'vue';

  export default defineComponent({
    name: 'Comp',
    setup(props, ctx) {
      const inputRef = ref('');

      const getInputRefValue = () => {
        return inputRef.value;
      }

      return {
        inputRef
      };
    }
  });
</script>

<template>
  <input
    type="text"
    placeholder="请输入。。。"
    v-model:modelValue="inputRef"
  />
</template>

修改:

  1. 在脚本(<script> 或者 <script setup>)中,访问 ref 的值需要使用 ref.value进行修改:
import { ref } from 'vue';

const inputRef = ref('');

const getInputRefValue = () => {
  return inputRef.value;
}

const setInputValue = (newValue) => {
  inputRef.value = newValue;
}
  1. 不建议在模板中使用句柄式回调修改 ref 的值!!!

在真实的 DOM 节点中绑定 ref

  • 和 options API 一样,ref 也可以绑定元素引用和组件引用
  • 引用绑定完成后,在 onMounted 中的回调函数进行访问
<script>
  import { defineComponent, ref, onMounted } from 'vue';
  
  export default defineComponent({
    name: 'Comp',
    setup(props, ctx) {
      const domRef = ref(null);
      const keepAliveRef = ref(null);
      
      onMounted(() => {
        console.log(domRef.value);
        console.log(keepAliveRef.value);
      });
      
      return {
        domRef,
        keepAliveRef
      };
    }
  });
</script>

<template>
  <div>
    <input ref="domRef" />
    <keep-alive ref="keepAliveRef"></keep-alive>
  </div>
</template>

注意点:

  1. ref 对象是可更改的,也就是说你可以为 .value 赋予新的值。
  2. ref 对象是响应式的,即所有对 .value 的操作都将被追踪,并且写操作会触发与之相关的副作用。
  3. 如果将一个对象赋值给 ref,那么这个对象将通过 reactive() 转为具有深层次响应式的对象。这也意味着如果对象中包含了嵌套的 ref,它们将被深层地解包。
  4. 如果您此时依然想要的是浅代理的对象, 请使用 shallowRef()