Vue3.0 + Vite + Ts 关于ref和v-model对应的字段的感悟(新的获取 dom 方式)

530 阅读1分钟

一、问题发现:

有这么一段代码

<input
   type="text"
   class="newAdress"
   ref="newAdress"
   placeholder="请输入地址"
   v-model="newAdress"
/>

ref 和 v-model 对应的字段名称都一样(前提:newAdress 的值为空(不为空也不影响))

如果运行后会发现,输入框的内容显示变成:[[object HTMLInputElement]]

image.png

浏览器打印字段 newAdress 发现值变成了 input 的dom节点了。如下图

image.png

那么是不是获取元素dom的方式,除了通过 ctx.ref或 proxy.ref 或 proxy.ref 来获取dom元素了

二、实践:

上代码:分别声明两个变量 newAdress 和 newAdressRef 来赋给 v-model 和 ref

<template>
    <input
      type="text"
      class="newAdress"
      ref="newAdressRef"
      placeholder="请输入地址"
      v-model="newAdress"
    />
</template>

<script setup lang="ts">
import { ref, provide, reactive } from "@vue/reactivity";
import { onMounted } from "vue";
const newAdress = ref("")
const newAdressRef = ref("")
</script>

对dom操作前

image.png

在onMounted中添加一句 newAdressRef.value.style.background = "red";

<script setup lang="ts">
import { ref, provide, reactive } from "@vue/reactivity";
import { onMounted } from "vue";
const newAdress = ref("")
const newAdressRef = ref("")
onMounted(() => {
  newAdressRef.value.style.background = "red";
});
</script>

结果:

image.png

发现可行。 其他实践结果说明: 声明 dom 上的 ref 对应的字段只能在使用 ref ,不能使用 reactive 来声明,否则获取不到 dom。同时元素的 dom 值是放在 value 字段中,需要如此操作 newAdressRef.value.style.background = "red";

项目打包后:在服务器运行:结果和上图一样

三、优缺点:

优点:相对于使用ctx.ref或 proxy.ref 或 proxy.ref的方式来获取Dom,更加快捷方便。 确定:无论哪个都要声明变量,没有 Vue2 无脑 this 来的舒服。

本人仍在在学习 Vue3.0 + Vite + Ts 中,如有错误,请指教。