[英]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.