vue.js - VueJS - 单击时交换组件

标签 vue.js

在我的应用程序中,我有很多按钮。当我按下按钮时,我想加载一个模板(替换所选按钮):

模板:

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)。

最佳答案

您需要将变量绑定(bind)到 :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

关于vue.js - VueJS - 单击时交换组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39391218/

相关文章:

vue.js - 如何正确地将 JW Player 脚本嵌入到 VueJS 中?

javascript - 在 javascript 中重新执行脚本而不再次调用服务器

object - 如果 vue.js 2 上的对象为空,如何添加条件?

javascript - 在 Vue.JS 中观察动态嵌套数据?

javascript - 在页面加载时获取数据并将其分配给 Vue JS 中的选择选项

vue.js - 如何将数组中的 mutil 对象与 lodash 合并?

javascript - Vue JS 组件未捕获引用错误 : Vue is not defined

javascript - 如何在 Vue Test Utils/Jest 中模拟 Web API?

javascript - 获取路由器参数到 Vuex Action

javascript - 我如何从这个 vue.js 对象创建购物车