Vue.js: Only load component if user clicks button

Viewed 11862

I have code that looks like the code below. how do I set this up so the components "dataPart1' and "dataPart2" won't load unless a user clicks a button to view the data? In other words, I don't want the data to just automatically show, but only if the user chooses to see it via a button click option.

var app = new Vue({
  el: '#data',
  data: {
    show: true,
    something: true,
  },
  components: {
    dataPart1,
    dataPart2
  },
  ...other stuff...
  }
});
1 Answers

In order to conditionally display content in the templates (text, html, components, etc), we can use conditional rendering of Vue.js and specifically v-if directive.

Short explanation: we can display content depending on certain variables defined in our component. And change value of that variable on certain events, e.g. button click.

Please, take a look at example on CodeSandbox of loading two components conditionally on buttons clicks.

In App.vue file, we have 2 buttons that trigger a handler on click and display component's if corresponding value is true.

Edit Vue Template

Related