简体   繁体   English

Vue3 TS 使用 ref 获取输入值

[英]Vue3 TS get value of input with ref

Seems to be so simple problem, however, I don't see any consistent documentation of Vue 3 typescript on how to access an input field and get its value from a function.似乎是一个如此简单的问题,但是,我没有看到关于如何访问输入字段并从 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,
  }
});

PS.附言。 very new with Vue and typescript. go easy on me:) Vue 和 typescript 非常新。go 对我来说很容易:)

I think you just can use the v-model binding .我想你可以使用v-model binding

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

If you need to run a function on change, you could use watch() .如果您需要在更改时运行 function,您可以使用watch() Remember to import watch from 'vue'.请记住从“vue”导入手表。

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

Hope this helps.希望这可以帮助。

PS: a bit off topic (but since you are fairly new to vue): you also can use <script setup> , which simplifies the setup function. See docs. PS:有点题外话(但因为你是 vue 的新手):你也可以使用<script setup> ,它简化了设置 function。请参阅文档。

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

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