vue组件切换_demo

项目参考:36_动态组件_哔哩哔哩_bilibili

项目结构:

App.vue

<template>
  <component :is="Component"></component>
  <button @click="switchHandle">switch Component</button>
</template>
<script>
  import ComponentA from './components/ComponentA.vue';
  import ComponentB from './components/ComponentB.vue';

  export default {
    data() {
      return {
        Component: "ComponentA"
      }
    },
    components: {
      ComponentA,
      ComponentB
    },
    methods: {
      switchHandle() {
        this.Component = this.Component == "ComponentA" ? "ComponentB" : "ComponentA"
      }
    }
  }
</script>

  

main.js

// 将项目原来引入的css样式删掉
import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount('#app')

  

ComponentA.vue

<template>
    <h3>component a</h3>
</template>

  

ComponentB.vue

<template>
    <h3>component b</h3>
</template>

  

运行效果

 

posted @ 2023-09-03 18:30  hemeiwolong  阅读(12)  评论(0编辑  收藏  举报