繁体   English   中英

Vue3 TS 使用 ref 获取输入值

[英]Vue3 TS get value of input with ref

似乎是一个如此简单的问题,但是,我没有看到关于如何访问输入字段并从 function 获取其值的 Vue 3 typescript 的任何一致文档。

<template>
  <Field
    type="text"
    name="test"
    ref="input"
  />

  <span @click="testFunc()">Test</span>
</template>

export default defineComponent({
...
setup() {
  const input = ref<HTMLInputElement | null>(null);

  const testFunc = () => {
    if (input.value) {
       console.log(input.value.value); // always undefined
    }
  };

  return {
   input,
   testFunc,
  }
});

附言。 Vue 和 typescript 非常新。go 对我来说很容易:)

我想你可以使用v-model binding

<template>
  <Field
    type="text"
    name="test"
    v-model="input"
  />
</template>

如果您需要在更改时运行 function,您可以使用watch() 请记住从“vue”导入手表。

watch(input, (newValue, oldValue)=>{
   console.log(newValue, oldValue)
})

希望这可以帮助。

PS:有点题外话(但因为你是 vue 的新手):你也可以使用<script setup> ,它简化了设置 function。请参阅文档。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM