Home > Mobile >  How to display object with the selected value in dropdown
How to display object with the selected value in dropdown

Time:01-18

I created object like you see in below:

export default {
    data() {
        return {
            language: {
                "en": {
                    welcomeMsg: "Welcome to New York City"
                },
                "de": {
                    welcomeMsg: "Wilkommen New York Stadt"
                }
            },
        };
    },
};

And I have a dropdown menu, the selected variable in the dropdown menu is "lang". So when I run this code:

<h6 v-for="l in language">
    <div>{{ l.welcomeMsg }}</div>
    <div>{{lang}}</div>
</h6>

The display is like this: Welcome to New York City Wilkommen New York Stadt en en (selected value is en in the dropdown, therefore it came as "en")

What I am trying to achieve, I want to put if state in h6 tag and I only want to display selected value in the dropdown. For example if 'lang' is 'en', it should display welcomeMsg which is "Welcome to New York City". if it is de, the other one.

Can you help me with this? Do you think I created object wrong?

CodePudding user response:

You can simply access the language object by the selected value

<h6>{{ language[lang]['welcomeMsg'] }}</h6>

Watch the demo here

CodePudding user response:

Suggestion : Try to use vue-I18n plugin to easily integrates localization features to your Vue.js application.

Working Demo as per OP :

new Vue({
  el: '#app',
  data: {
    language: {
      "en": {
        welcomeMsg: "Welcome to New York City"
      },
      "de": {
        welcomeMsg: "Wilkommen New York Stadt"
      }
    },
    selectedLang: '',
    updatedMsg: ''
  },
    methods: {
        updateWelcomeMsg(event) {
                this.updatedMsg = this.language[event.target.value].welcomeMsg;
        }
    }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
<select name="lang" @change="updateWelcomeMsg($event)" v-model="selectedLang">
   <option value="en">EN</option>
   <option value="de">DE</option>
</select>

<div>{{updatedMsg}}</div>
</div>

  •  Tags:  
  • Related