Vue.js 中可互换的动态组件

你是否曾在 Vue.js 中需要在相同的安装点中切换各种任意组件?当然,这不是一个超常见的问题,但如果你实现了自己的路由器,或者你不想使用插槽的某种容器组件,那你会做的事情。

无论如何,在Vue中使用<component></component>标签来做到这一点非常简单。

输入 标签

从概念上讲,<component>标签是非常简单的,它只需要一个字符串(或组件定义):is prop. Vue 然后查看该字符串所引用的组件,并将其转换为<component>标签。

使用例子:

 1<template>
 2  <component :is="dynamicComponent"></component>
 3</template>
 4
 5<script>
 6
 7// Register another component to render in this one dynamically.
 8import Vue from 'vue';
 9
10Vue.component('some-other-component', {
11  template: `<p>Wheee</p>`
12});
13
14export default {
15  data() {
16    return {
17      dynamicComponent: `some-other-component`
18    }
19  }
20}
21</script>

或者简单地使用一个组件定义:

 1<template>
 2  <component :is="dynamicComponent"></component>
 3</template>
 4
 5<script>
 6export default {
 7  data() {
 8    return {
 9      dynamicComponent: {
10        template: `<p>Wheee</p>`
11      }
12    }
13  }
14}
15
16</script>

或者反应性地切换具有计算性能的组件...

 1<template>
 2  <component :is="dynamicComponent"></component>
 3</template>
 4
 5<script>
 6export default {
 7  props: {
 8    value: Boolean
 9  },
10
11  computed: {
12    dynamicComponent() {
13      if(value) {
14        return 'component-special';
15      } else {
16        return 'component-default';
17      }
18    }
19  }
20}
21</script>

当然,您可以从 Vue 实例中使通过的组件或其他任何内容可访问。

活生生

现在,使用<component>渲染的任何组件都会被完全破坏,当另一个组件被渲染到其位置时,如果重新添加,则会被重新创建。

如果您希望使用<component>标签渲染的组件(或以条件渲染)在不再渲染时不会被破坏,只需将<component>标签嵌入<keep-alive>标签中:

1<template>
2  <div>
3    <keep-alive>
4      <component :is="dynamicComponent"></component>
5    </keep-alive>
6  </div>
7</template>
Published At
Categories with 技术
Tagged with
comments powered by Disqus