背景
- 在 Vue 3 中,动态组件的写法与 Vue 2 基本相同,因为这是一个 Vue 的核心功能,并且在 Vue 3 中得到了保留。
- 不过,Vue 3 引入了 Composition API,这允许你以不同的方式组织组件逻辑,但这并不影响动态组件的基本用法。
以下是一个使用 Vue 3 和 Composition API 的例子,展示了如何动态地切换组件:
<template> <div> <button @click="setCurrentView('Home')">Home</button> <button @click="setCurrentView('About')">About</button> <Component :is="currentView"/> </div>
</template> <script>
import { ref } from 'vue';
import Home from './Home.vue';
import About from './About.vue'; export default { setup() { const currentView = ref('Home'); const setCurrentView = (viewName) => { currentView.value = viewName; }; return { currentView, setCurrentView, }; }, /* 1.果你在单文件组件中,并且这些组件是在当前文件之外的其他地方定义的!2.你仍然需要在 components 选项中注册它们,即使你在 setup 函数中使用了它们。 3.然而,对于动态组件来说,由于你是通过 :is 属性来指定要渲染的组件的, 4.所以通常不需要在 components 选项中预先注册所有可能的组件。 5.下面的 components 选项是注释掉的,因为它在这个特定的动态组件例子中不是必需的components: { Home, About }, */
};
</script>