2016-09-08 2 views
1

В моем приложении у меня много кнопок. Когда я нажимаю его я хотел бы загрузить шаблон (который заменяет эту кнопку):VueJS - компонент Swap при нажатии

Шаблоны:

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

Смежные вопросы