自学内容网 自学内容网

vue如何实现组件切换

一、使用条件渲染 (v-if)

<template>
    <div>
        <button @click="currentView = 'ComponentA'">Show Component A</button>
        <button @click="currentView = 'ComponentB'">Show Component B</button>
        <component-a v-if="currentView === 'ComponentA'"></component-a>
        <component-b v-if="currentView === 'ComponentB'"></component-b>
    </div>
</template>
<script>
import ComponentA from './ComponentA.vue';
import ComponentB from './ComponentB.vue';
export default {
    data() {
        return {
            currentView: 'ComponentA'
        };
    },
    components: {
        ComponentA,
        ComponentB
    }
};
</script>

二、使用动态组件 (component)

<template>
    <div>
        <button @click="currentView = 'ComponentA'">Show Component A</button>

        <button @click="currentView = 'ComponentB'">Show Component B</button>

        <component :is="currentView"></component>
    </div>
</template>

<script>
import ComponentA from './ComponentA.vue';

import ComponentB from './ComponentB.vue';

export default {
    data() {
        return {
            currentView: 'ComponentA'
        };
    },

    components: {
        ComponentA,

        ComponentB
    }
};
</script>

 三、点击按钮切换组件

<template>
  <div>
    <button @click="toggleComponent">切换组件</button>
    <div v-if="showComponent">
      <ComponentA />
    </div>
    <div v-else>
      <ComponentB />
    </div>
  </div>
</template>

<script>
import ComponentA from './ComponentA.vue'
import ComponentB from './ComponentB.vue'

export default {
  data() {
    return {
      showComponent: true
    }
  },
  methods: {
    toggleComponent() {
      this.showComponent = !this.showComponent
    }
  },
  components: {
    ComponentA,
    ComponentB
  }
}
</script>
<template>
  <div>
    <button @click="toggleComponent">切换组件</button>
    <transition name="fade">
      <component :is="currentComponent" />
    </transition>
  </div>
</template>

<script>
import ComponentA from './ComponentA.vue'
import ComponentB from './ComponentB.vue'

export default {
  data() {
    return {
      currentComponent: 'ComponentA'
    }
  },
  methods: {
    toggleComponent() {
      this.currentComponent = this.currentComponent === 'ComponentA' ? 'ComponentB' : 'ComponentA'
    }
  },
  components: {
    ComponentA,
    ComponentB
  }
}
</script>

<style>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}
</style>

 


原文地址:https://blog.csdn.net/weixin_36617251/article/details/143824408

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!