vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > vue组件切换

vue实现组件切换效果的三种功能

作者:想你的风吹到了瑞士

这篇文章主要为大家介绍了在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>

到此这篇关于vue实现组件切换效果的三种功能的文章就介绍到这了,更多相关vue组件切换内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文