0

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

2
  • Don't you need i18n here? github.com/kazupon/vue-i18n Commented Dec 23, 2015 at 19:32
  • Thank you for the plugin @rmagnum2002! The problem is that the data structure has to be this one title{en:'hello',es:'hola'} instead of es:{title:'hola'},en:{title:'hello'} Commented Dec 24, 2015 at 16:21

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much, this is exactly what I was looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.