背景
以下是一个使用 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>