VueJS - 单击时交换组件 [英] VueJS - Swap component on click
问题描述
在我的应用程序中,我有很多按钮.当我按下按钮时,我想加载一个模板(替换所选按钮):
模板:
Vue.component('component-1', {...});Vue.component('component-2', {...});
按钮:
<button>Button1</button><button>Button2</button>
在这种情况下,当我按下 Button1
时,div toReplace
的内容应该是 component-1
.当然,每个组件都应该有一个关闭"按钮,在按下时会再次显示按钮(简而言之,div toReplace
).
您需要将一个变量绑定到 :is
属性.并在按钮单击时更改此变量.您还需要将它与一些 v-show
条件结合起来.像这样:
<div :is="currentComponent"></div><div v-show="!currentComponent" v-for="componentsArray 中的组件"><button @click="swapComponent(component)">{{component}}</button>
<button @click="swapComponent(null)">关闭</button>
new Vue({el: '身体',数据: {当前组件:空,componentsArray: ['foo', 'bar']},成分: {'富':{模板:'<h1>Foo 组件</h1>'},'酒吧': {模板:'<h1>条形组件</h1>'}},方法: {交换组件:功能(组件){this.currentComponent = 组件;}}});
这是一个简单的例子:
http://jsbin.com/miwuduliyu/edit?html,js,控制台,输出
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.
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
这篇关于VueJS - 单击时交换组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!