vue3+ts点击按钮获取输入框内容
时间: 2023-09-17 17:09:07 浏览: 92
可以通过在 Vue 组件中使用 ref 来获取输入框元素,然后在 TypeScript 中定义对应的变量类型来获取输入框的值。
以下是一个示例代码:
```vue
<template>
<div>
<input type="text" ref="inputRef" />
<button @click="handleClick">获取输入框内容</button>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
export default defineComponent({
setup() {
const inputRef = ref<HTMLInputElement | null>(null);
const inputValue = ref<string>('');
const handleClick = () => {
if (inputRef.value) {
inputValue.value = inputRef.value.value;
}
console.log(inputValue.value);
};
return {
inputRef,
handleClick,
inputValue,
};
},
});
</script>
```
在这个示例中,我们首先使用 ref 创建了一个 inputRef 变量,它的类型是 HTMLInputElement 或者 null,因为在组件初始化的时候,input 元素还没有被挂载到 DOM 上,所以初始值为 null。
然后,我们定义了一个 inputValue 变量,它的类型是 string,用于保存输入框的值。
在 handleClick 函数中,我们首先判断 inputRef.value 是否存在,如果存在,说明 input 元素已经被挂载到 DOM 上了,我们就可以通过 inputRef.value.value 来获取输入框的值,然后将其赋值给 inputValue.value。
最后,我们将 inputValue.value 输出到控制台中。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)