15

In my application I have many buttons. When I press it the button I would like to load a template (that replaces the selected button):

Templates:

Vue.component('component-1', {...});
Vue.component('component-2', {...});

Buttons:

<div id="toReplace">
  <button>Button1</button>
  <button>Button2</button>
</div>

In this case, when I press Button1 the content of the div toReplace should be component-1. Sure, each component should have a "close" button that will show the buttons again (in short, the div toReplace) on press.

2 Answers 2

27

You need to bind a variable to :is property. And change this variable on button click. Also you will need to combine it with some v-show condition. Like so:

<div id="toReplace">
    <div :is="currentComponent"></div>
    <div v-show="!currentComponent" v-for="component in componentsArray">
      <button @click="swapComponent(component)">{{component}}</button>
    </div>
</div>
<button @click="swapComponent(null)">Close</button>
new Vue({
  el: 'body',
  data: {
    currentComponent: null,
    componentsArray: ['foo', 'bar']
  },
  components: {
    'foo': {
      template: '<h1>Foo component</h1>'
    },
    'bar': {
      template: '<h1>Bar component</h1>'
    }
  },
  methods: {
    swapComponent: function(component)
    {
      this.currentComponent = component;
    }
  }
});

Here is quick example:

http://jsbin.com/miwuduliyu/edit?html,js,console,output

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

2 Comments

How would you pass props to the component in this method?
@srik To also pass dynamic props, you gotta use v-bind without argument, proving it with an object of prop names and values.
1

You can use v-bind:is="CurrentComponent" and @click=ChangeComponent('SecondComponent'). The argument has to be a string. To use the <component/> make sure your ExampleComponent has a slot

<Template>
  <div>
    <ExampleComponent>
      <component v-bind:is = "CurrentComponent"/>
    </ExampleCompoent>
    <button @click="ChangeComponent('SecondComponent')">
    </button>
  </div>
</template>

<script>
  import ExampleComponent from '@/components/ExampleComponent.vue'
  import SecondComponent from '@/components/SecontComponent.vue'
  export default{
    ...
    data(){
      return{
        CurrentComponet:null
      }
    }
    methods:{
      ChangeComponent(NewComponent){
        this.CurrentComponent = NewComponent
    }

Comments

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.