rogervila
rogervila

Reputation: 1064

Switch between object properties in Vue.js

QUESTION

I would like to know how can I switch between object properties in Vue.js.

Here is a visual example:

var vm = new Vue({
    el: '#app',
    data:{
        myObject:{
            one: 'lorem',
            two: 'ipsum'
        }
    }
});

I want to be able to change from {{ myObject.one }} to {{ myObject.two }}, on the same place in the html, but I don't know if it's possible.

I have tried two solutions, but they require more code and resources:

1) repeat the html for every object property and use v-show

2) use only one property and change its content via ajax

Is there a better way that not requires multiple ajax calls or repeating html?

CONTEXT

I want to make a multilingual app, where the content changes clicking in a button. The code looks like this:

    <div id="app">
        <h1>{{ title.en }}</h1>
    <div>

    <script>
        var vm = new Vue({
            el: '#app',
            data:{
                title:{
                    en: 'Hello',
                    es: 'Hola'
                }
            }
        });
    </script>

I want to switch from {{ title.en }} to {{ title.es }}

Thank you very much

Upvotes: 0

Views: 440

Answers (1)

Bill Criswell
Bill Criswell

Reputation: 32921

You can set a lang variable to something like 'en' and use title[lang]. This will be the same as calling title.en.

new Vue({
  el: '#app',
  data: {
    lang: 'en',
    title: {
      en: 'Hello',
      es: 'Hola'
    }
  }
});

<div id="app">
  <ul>
    <li @click="lang = 'en'">English</li>
    <li @click="lang = 'es'">Spanish</li>
  </ul>
  <h1>{{ title[lang] }}</h1>
</div>

Upvotes: 2

Related Questions