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

模板:

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

按钮:

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

在这种情况下,当我按下Button1时,div toReplace的内容应该是component-1.

推荐答案

您需要将一个变量绑定到: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相关问答推荐

Vue CDN的html工作,但v—如果不工作

如何将$validator实例注入到使用组合API语法的Vue2.7应用程序中

使用计算(computed)属性更改视图

Vue CLI - 编译后将配置文件保留为外部

如何从特定索引呈现 v-for

如何渲染数组以 Select 选项 vue.js

有条件地在 Vue 中添加一个 CSS 类

未捕获的错误:[vue-composition-api] 必须在使用任何函数之前调用 Vue.use(plugin)

自定义props类型

如何在 Node.js 服务器上部署 Vue.js 应用程序

如何使用 vue.js 获取所选选项的索引

Javascript/vue.js 接收json

未捕获的类型错误:c.querySelectorAll 不是函数

基于条件的VueJS HTML元素类型

Vue 动态组件事件绑定

Vue-i18n '无法读取 Proxy.Vue.$t 处未定义的属性 '_t'

标签中的 href 赋值

根据nuxt中的url参数动态加载组件

如何在 Vue 数据对象中运行函数?

vue-cli@3 没有可用于依赖类型的模块工厂:CssDependency