VueJS - 点击时交换组件

Mis*_*e83 6 vue.js

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

模板:

Vue.component('component-1', {...});
Vue.component('component-2', {...});
Run Code Online (Sandbox Code Playgroud)

纽扣:

<div id="toReplace">
  <button>Button1</button>
  <button>Button2</button>
</div>
Run Code Online (Sandbox Code Playgroud)

在这种情况下,当我按Button1div的内容时toReplace应该是component-1.当然,每个组件都应该有一个"关闭"按钮,按钮会再次显示按钮(简称div toReplace).

GON*_*ONG 15

您需要将变量绑定到:isproperty.并在按钮单击时更改此变量.您还需要将其与某些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>
Run Code Online (Sandbox Code Playgroud)
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;
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

这是一个简单的例子:

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

  • 在这个方法中,你将如何将 props 传递给组件? (2认同)