无需使用I18n插件,如何在Vue的v-for循环中实现{{item.title}}的翻译?
Let’s break this down into a quick fix that works with your current setup, plus a more maintainable approach for long-term use.
Quick Fix: Pass item.title Directly to Your translate Method
Your existing translate method is designed to take a property name and pull the corresponding value from your active language object. Since your items array uses English strings as title values, you can directly pass item.title to the method in your template:
Updated Template Code
<div class="col-md-6 col-lg-4"> <div class="box my-5" v-for="(item, index) in items" :key="index"> <div class="innerBox"> <router-link to="/sixthPage"> <div class="card Fcard d-flex flex-row justify-content-center align-items-center" style="padding: 1rem 2rem !important"> <p>{{ translate(item.title) }}</p> <!-- This line is modified --> </div> </router-link> <router-view></router-view> </div> </div> </div>
Double-Check Your Language File Structure
Make sure your language exports match the exact title strings in your items array. For example:
en.js
export default { 'Protect Privacy': 'Protect Privacy', 'Bypass Censorship': 'Bypass Censorship', 'Faster Internet': 'Faster Internet', 'I do not want to specify': 'I do not want to specify' }
tr.js
export default { 'Protect Privacy': 'Gizliliği Koru', 'Bypass Censorship': 'Sansürü Atlat', 'Faster Internet': 'Daha Hızlı İnternet', 'I do not want to specify': 'Belirtmek İstemiyorum' }
More Maintainable Approach: Use Semantic Keys
Using raw English text as translation keys can get messy if you ever need to update the default wording. A better pattern is to use semantic keys instead:
Step 1: Update Your items Array
Replace raw titles with meaningful keys:
data () { return { items: [ { titleKey: 'protect_privacy' }, { titleKey: 'bypass_censorship' }, { titleKey: 'faster_internet' }, { titleKey: 'no_specification' } ], lang: window.navigator.language.split('-')[0], // Handles regional codes like 'en-US' } }
Step 2: Adjust Language Files
Update your language packages to use these keys:
en.js
export default { protect_privacy: 'Protect Privacy', bypass_censorship: 'Bypass Censorship', faster_internet: 'Faster Internet', no_specification: 'I do not want to specify' }
tr.js
export default { protect_privacy: 'Gizliliği Koru', bypass_censorship: 'Sansürü Atlat', faster_internet: 'Daha Hızlı İnternet', no_specification: 'Belirtmek İstemiyorum' }
Step 3: Update the Template
Use the new key with your translate method:
<p>{{ translate(item.titleKey) }}</p>
Bonus: Add Fallbacks for Missing Translations
To avoid broken text if a key isn’t found in the active language, tweak your translate method:
methods: { translate(prop) { return this[this.lang]?.[prop] || prop; // Fallback to the key itself if translation is missing } },
内容的提问来源于stack exchange,提问作者Kerem Unce




