有条件地定义了VueJS中的导入组件

发布于 2025-02-10 10:39:41 字数 519 浏览 1 评论 0原文

可以说,我在VUEJS中有一个父母组件,其中有两个版本的子组件(a,b)。 有办法做这样的事情吗?动态定义组件,而不是使用V-IF和V-ELSE?

<template>
    <Child />
</template>

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

export default {
  name: 'Parent',
  components: {
    Child: () => {
      if (renderA === true) {
        return A;
      } else {
        return B;
      }
    },
  },
  computed: {
    renderA() {
      return Math.random() < 0.5;
    },
  }
}
</script>

Lets say i have a parent component in VueJs with two versions of child component (A, B).
Is there a way to do something like this? Dynamically define component rather than using v-if and v-else?

<template>
    <Child />
</template>

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

export default {
  name: 'Parent',
  components: {
    Child: () => {
      if (renderA === true) {
        return A;
      } else {
        return B;
      }
    },
  },
  computed: {
    renderA() {
      return Math.random() < 0.5;
    },
  }
}
</script>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

远山浅 2025-02-17 10:39:41

您可以使用&lt;组件&gt;标签。 vue docs

<template>
    <component :is="toRender" />
</template>

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

export default {
  name: 'Parent',
  computed: {
    toRender() {
      return Math.random() < 0.5 ? A : B
    },
  }
}
</script>

You can use the <component> tag. Vue Docs

<template>
    <component :is="toRender" />
</template>

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

export default {
  name: 'Parent',
  computed: {
    toRender() {
      return Math.random() < 0.5 ? A : B
    },
  }
}
</script>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文