2016-09-08 140 views
1

在我的应用程序中,我有很多按钮。当我按下它,我想加载模板(即替换该按钮):VueJS - 点击交换组件

模板:

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

按钮:

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

在这种情况下,当我按下Button1内容的div toReplace应该是component-1。 当然,每个组件应该有一个“关闭”按钮,在按下时再次显示按钮(简而言之,div toReplace)。

回答

8

您需要将变量绑定到:is属性。并在点击按钮时更改此变量。你也需要将它与v-show条件相结合。像这样:

<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; 
    } 
    } 
}); 

下面是简单的例子:

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