VueJS - Swap component on click

后端 未结 1 1268
南笙
南笙 2021-02-14 12:43

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.com         


        
相关标签:
1条回答
  • 2021-02-14 13:37

    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

    0 讨论(0)
提交回复
热议问题