javascript - Vue.js动态挂载单文件组件

标签 javascript vue.js

我有一个单一的文件组件 Main.Vue

我还有另外三个单文件组件 A.vueB.vueC.vue

我希望每次都能在 Main.Vue 中显示不同的组件。我所做的是:

<template>
<div>
<a v-if="isAVisible" ></a>
<b v-if="isBVisible" ></a>
</div>
</template>

<script>
import A from './A.vue';
import B from './B.vue';
...

这可行,但不完全是我想要的。我想要一个不同的文件 Factory.js,它会导入所有组件 ABC ,.. 并且具有返回我的组件的函数,我可以以某种方式在 Main.vue 中使用它。这是我试过的 Factory.js 的样子:

import A from './A.vue';
import B from './B.vue';
function getComponent(){
  if (..)
    return new A();
  else if (..)
    return new B();
  ...
}

这根本不起作用。 我想要工厂文件方法,因为:

1)我想把它拆分成不同的工厂文件

2) 我想将数据“附加”到每个组件。所以我将有一个对象,其中包含返回实际组件的函数 + 一些附加数据,如“名称”

有什么办法吗?

最佳答案

使用Vue的动态组件

你可以使用 Dynamic Components在组件之间动态切换。您需要将组件定义对象绑定(bind)到 component 元素的 is 属性——Vue 关于此的文档非常清楚。下面也是一个简单的例子:

<template>
  <component :is="activeComponent"></component>
</template>
import componentA from 'component/a';
import componentB from 'component/b';

export default {
  components: {
    componentA,
    componentB,
  },

  data() {
    return {
      activeComponent: 'componentA',
    },
  },
};

您可以直接将组件定义对象绑定(bind)到数据属性本身:

import componentA from 'component/a';
import componentB from 'component/b';

export default {
  data() {
    return {
      activeComponent: componentA,
    };
  },
};

要切换组件,您可以通过编程方式更改 activeComponent 的值。

使用渲染函数

使用组件 render functions 可以实现动态挂载组件的更强大方式。 .为此,我们必须创建 我们自己的版本 Vue 的 component 元素——我们将其称为 ElementProxy:

import componentA from 'component/a';
import componentB from 'component/b';

export default {
  components: {
    componentA,
    componentB,
  },

  props: {
    type: {
      type: String,
      required: true,
    },
    props: {
      type: Object,
      default: () => ({}),
    },
  },

  render(createElement) {
    const { props: attrs } = this;
    return createElement(element, { attrs });
  },
};

您现在可以使用 ElementProxy 来代理元素。这样做的额外好处是您可以将 props 作为对象传递,这将解决将 props 传递给具有不同模型的动态组件的问题。

<template>
  <element-proxy :type="activeComponent" :props="props"></element-proxy>
</template>
import ElementProxy from 'components/elementProxy';

export default {
  components: {
    ElementProxy,
  },

  data() {
    return {
      activeComponent: 'componentA',
      props: { ... },
    };
  },
};

进一步阅读

关于javascript - Vue.js动态挂载单文件组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43799416/

相关文章:

javascript - 防止输入无效日期的 AngularJS 指令

javascript - Android 下的 Firefox/Chrome 在键入字母时不会触发 OnKeyPress、onKeyDown、onKeyUp 事件

javascript - 表达式解析 : how to tokenize

javascript - 如何将应用程序数据传递到 VueRouter 组件

javascript - 如何在 nuxt 中使用 google recaptcha?

mysql - 无法获取 laravel 中的关系数据

javascript - HighChart 设置新数据

webpack - 如何使用 Vuejs+Webpack 包含外部 sass 目录?

javascript - Vue 3 在安装之前访问 DOM 元素

JavaScript: "function onload() {}"与 "onload = function() {}"有何不同?