<template>
  <div>
    <!-- 使用动态组件 -->
    <component :is="currentComponent"></component>
    <!-- 切换组件按钮 -->
    <button @click="changeComponent('Home')">Home</button>
    <button @click="changeComponent('About')">About</button>
  </div>
</template>
<script>
// 引入组件
import Home from './components/Home.vue';
import About from './components/About.vue';
export default {
  name: 'App',
  data() {
    return {
      // 当前显示的组件名称
      currentComponent: 'Home'
    };
  },
  methods: {
    // 切换当前显示的组件
    changeComponent(componentName) {
      this.currentComponent = componentName;
    }
  },
  components: {
    // 注册组件
    Home,
    About
  }
};
</script>
<style scoped>
/* 样式部分可以根据需要添加 */
</style><component :is="currentComponent">:这是 Vue 的动态组件语法,is 属性决定了当前渲染哪个组件。currentComponent 是一个变量,它的值可以是组件的名称或直接是组件对象。data():在 data 中定义了 currentComponent 变量,用来存储当前要显示的组件名称,默认为 'Home'。methods:定义了 changeComponent 方法,用于切换当前显示的组件。components:注册了 Home 和 About 组件,以便可以在模板中使用它们。changeComponent 方法,传入不同的组件名称来切换显示的组件。这种方式可以灵活地在多个组件之间进行切换,而不需要重复编写相同的代码。
上一篇:vue3框架搭建
下一篇:vue3开发
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站