1

I want to build an app in vue.js where you can dynamically switch between app views without page reloading. What is the best way to do it? And why this code doesn't work? Thank you!

var View01 = {
    template: `<button @click="swapComponent('view-02')" type="submit">NEXT VIEW</button>`
}
var View02 = {
    template: `<button @click="swapComponent('view-01')" type="submit">BACK TO PREVIOUS VIEW</button>`
}

var vm = new Vue({
    el: '#app',
    data: {
        currentComponent: 'view-01'
    },
    components: {
        'view-01': View01,
        'view-02': View02,
    },
    methods: {
        swapComponent: function(component) {
            this.currentComponent = component;
        }
    }
})
1
  • 1
    Just use the vue-router lib. Commented Nov 27, 2017 at 14:11

1 Answer 1

8

You're trying to call a parent method from the child components. You need to pass the method as a prop so it is in the child's scope.

var View01 = {
  template: `<button @click="swapComponent('view-02')" type="submit">NEXT VIEW</button>`,
  props: ['swapComponent']
}
var View02 = {
  template: `<button @click="swapComponent('view-01')" type="submit">BACK TO PREVIOUS VIEW</button>`,
  props: ['swapComponent']
}

var vm = new Vue({
  el: '#app',
  data: {
    currentComponent: 'view-01'
  },
  components: {
    'view-01': View01,
    'view-02': View02,
  },
  methods: {
    swapComponent: function(component) {
      this.currentComponent = component;
    }
  }
})
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script>
<div id="app">
  <div :is="currentComponent" :swap-component="swapComponent"></div>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.