【发布时间】:2021-12-11 19:50:59
【问题描述】:
我是 Vue 的初学者,希望得到您的帮助:)
我需要计算文本输入中的字符数(但只有数字)有v-model 并将结果显示为某个数字变量。输入是来自.json 文件的v-for 显示的内部元素。我的 App.vue 的示例代码:
<template>
<div class="product-item" v-for="(product,index) in products" :key="product.id">
<input type="text" v-model="coupon" @input='charCount()'>
{{ couponCharCount }}
</div>
</template>
<script>
import productsData from "../public/products.json";
name: 'App',
data() {
return {
products: productsData,
coupon: '',
couponCharCount: 0
}
},
methods: {
charCount() {
// only numbers filter
this.coupon = this.coupon.replace(/[^0-9.]/g,'');
// trying to count the characters
this.couponCharCount = this.coupon.length;
}
}
</script>
问题是当我输入一些值时,它适合每个v-for 元素input。需要做什么才能使其对每个 input 单独工作?
提前感谢您的帮助:)
【问题讨论】:
-
您目前遇到的错误是什么?
-
优惠券应该在产品上或使用for循环索引作为其索引制成数组,然后执行
{{charCount(product.coupon)}}或{{charCount(coupons[index])}} -
@LawrenceCherone 你能在我的代码中显示需要做什么吗?我将
v-model更改为v-model="coupons[index]"并添加到数据coupons: []现在我的方法什么都不返回 -
@Amaarrockz,然后当我在
input中输入一个值并尝试使用charCount()方法计算字符数时,该值在所有输入中都是重复的
标签: javascript vue.js vuejs3