vue3+vite动态监听输入框的值并计数,输入框绑定的数据为formData:{BZ: ""}
时间: 2023-12-14 10:38:36 浏览: 178
可以使用Vue 3的新特性——Composition API来实现动态监听输入框的值并计数,具体实现如下:
1. 在组件中引入 `reactive` 和 `watch`:
```js
import { reactive, watch } from 'vue';
```
2. 在组件中定义 `formData` 和 `count`:
```js
setup() {
const formData = reactive({
BZ: '',
});
const count = reactive({
num: 0,
});
}
```
3. 使用 `watch` 监听 `formData.BZ` 的变化,并在回调函数中统计字符数:
```js
setup() {
const formData = reactive({
BZ: '',
});
const count = reactive({
num: 0,
});
watch(
() => formData.BZ,
(val) => {
count.num = val.length;
}
);
}
```
4. 在模板中绑定输入框和计数器:
```html
<template>
<div>
<input v-model="formData.BZ" />
<p>{{ count.num }}</p>
</div>
</template>
```
完整代码如下:
```js
<template>
<div>
<input v-model="formData.BZ" />
<p>{{ count.num }}</p>
</div>
</template>
<script>
import { reactive, watch } from 'vue';
export default {
setup() {
const formData = reactive({
BZ: '',
});
const count = reactive({
num: 0,
});
watch(
() => formData.BZ,
(val) => {
count.num = val.length;
}
);
return {
formData,
count,
};
},
};
</script>
```
阅读全文