Vue循环生成的第二个输入框音译功能失效问题咨询
Hey there, let's sort out why your transliteration only works on the first input—this is a super common pitfall with dynamic elements!
The Root Cause
Looking at your code, every input generated by v-for uses the same static ID: transliterateTextarea2. In HTML, IDs must be unique across the entire DOM. When your transliteration script looks for an element by this ID, it only finds the first matching input and ignores all the rest. That's exactly why the second+ inputs don't work.
The Fix
We need two key changes to get this working for all inputs:
- Generate a unique ID for each input using the loop index.
- Ensure your transliteration logic initializes for every new input when you add a row.
Step 1: Update the Input ID to Be Dynamic
Modify your template to create a unique ID per input by appending the loop index:
<div class="row" v-for="(book, index) in Subsequent" :key="index"> <div class="col-md-8"> <div class="form-group label-floating"> <label class="control-label"> Details</label> <input type="text" class="form-control" v-model="book.seizuredetails" :id="`transliterateTextarea-${index}`" > </div> </div> </div> <a @click="addNewRow">Add Another</a>
Now each input gets a unique ID like transliterateTextarea-0, transliterateTextarea-1, etc.—no more conflicts.
Step 2: Initialize Transliteration for New Rows
If your transliteration feature uses an initialization function (let's say initTransliterate(id)), you need to call it every time you add a new row. Update your addNewRow method to target the new input's unique ID:
addNewRow() { // Add a new empty book entry to the array this.Subsequent.push({ seizuredetails: '' }); // Grab the index of the newly added item const newItemIndex = this.Subsequent.length - 1; // Initialize transliteration for the new input initTransliterate(`transliterateTextarea-${newItemIndex}`); }
This ensures every new input gets the transliteration functionality attached right when it's added.
Quick Note for Third-Party Libraries
If you're using a third-party transliteration tool (like Google's transliteration API), make sure you aren't only initializing it once on page load. Dynamic elements added after the initial render won't be picked up automatically—you have to explicitly set them up, which is exactly what the code above handles.
内容的提问来源于stack exchange,提问作者Wanderer

