Vue3 Composition API 中的动态组件

Ole*_*nko 17 vuejs3

Vue2动态组件的简单工作示例


<template>
    <div>
        <h1>O_o</h1>
        <component :is="name"/>
        <button @click="onClick">Click me !</button>
    </div>
</template>

<script>
    export default {
        data: () => ({
            isShow: false
        }),
        computed: {
            name() {
                return this.isShow ? () => import('./DynamicComponent') : '';
            }
        },
        methods: {
            onClick() {
                this.isShow = true;
            }
        },
    }
</script>
Run Code Online (Sandbox Code Playgroud)

一切正常,一切都很棒。我开始尝试它如何与 Composition API 一起使用。

<template>
    <div>
        <h1>O_o</h1>
        <component :is="state.name"/>
        <button @click="onClick">Click me !</button>
    </div>
</template>

<script>
    import {ref, reactive, computed} from 'vue'

    export default {
        setup() {
            const state = reactive({
                name: computed(() => isShow ? import('./DynamicComponent.vue') : '')
            });

            const isShow = ref(false);

            const onClick = () => {
                isShow.value = true;
            }

            return {
                state,
                onClick
            }
        }
    }
</script>
Run Code Online (Sandbox Code Playgroud)

我们启动后,该组件没有出现在屏幕上,尽管没有显示错误。

Ole*_*nko 25

您可以在此处了解有关“defineAsyncComponent”的更多信息 https://labs.thisdot.co/blog/async-components-in-vue-3

或者在官方网站上 https://v3.vuejs.org/api/global-api.html#defineasynccomponent

import { defineAsyncComponent, defineComponent, ref, computed } from "vue"

export default defineComponent({
setup(){
const isShow = ref(false);
const name = computed (() => isShow.value ? defineAsyncComponent(() => import("./DynamicComponent.vue")): '')

const onClick = () => {
    isShow.value = true;
  }
 }
})
Run Code Online (Sandbox Code Playgroud)


Ale*_*eks 15

以下是如何在 Vue 3 中加载动态组件。从/icons前缀为“icon-”的文件夹内的图标集合动态导入的示例。

BaseIcon.vue

<script>
import { defineComponent, shallowRef } from 'vue'

export default defineComponent({
  props: {
    name: {
      type: String,
      required: true
    }
  },
  setup(props) {
    // use shallowRef to remove unnecessary optimizations
    const currentIcon = shallowRef('')

    import(`../icons/icon-${props.name}.vue`).then(val => {
      // val is a Module has default
      currentIcon.value = val.default
    })

    return {
      currentIcon
    }
  }
})
</script>

<template>
    <svg v-if="currentIcon" width="100%" viewBox="0 0 24 24" :aria-labelledby="name">
      <component :is="currentIcon" />
    </svg>
</template>
Run Code Online (Sandbox Code Playgroud)

您不需要使用计算或观看。但是在加载和解析之前没有任何东西可以渲染,这就是v-if使用的原因。

UPD 因此,如果您需要通过更改 props 来更改组件(在我的例子中是图标),请使用watchEffect作为函数的包装器import

watchEffect(() => {
  import(`../icons/icon-${props.name}.vue`).then(val => {
    currentIcon.value = val.default
  })
})
Run Code Online (Sandbox Code Playgroud)

不要忘记从 vue 导入它 =)