Vue

前言

Vue中切换视图组件的方案大致有三种

1、roure-view 适合大幅度视图切换
2、v-if 适合小幅度组件切换
3、component 动态组件 

roure-view 切换视图组件

这个不多说了,之前的文章记录:Vue - route路由跳转


v-if 切换视图组件

  • 这个比较简单,如下:
<CommonOne v-if="true" />
<CommonTwo v-else />

component 切换视图组件

  • 效果图

在这里插入图片描述


  • home.vue
<template>
  <component :is="currentComponent" />

  <hr>

  <button @click="onChangeCurrent('CommonOne')">切换到组件一</button>
  <button @click="onChangeCurrent('CommonTwo')">切换到组件二</button>
</template>

<script>
import CommonOne from '@/components/common-one'
import CommonTwo from '@/components/common-two'
import { ref } from 'vue'

const currentComponent = ref('CommonOne')

export default {
  name: 'home',
  components: {
    CommonOne,
    CommonTwo
  },
  data () {
    return {
      currentComponent
    }
  },
  methods: {
    onChangeCurrent (val) {
      currentComponent.value = val
    }
  }
}
</script>
  • common-one.vue
<template>
  <div>组件一</div>
</template>
  • common-two.vue
<template>
  <div>组件二</div>
</template>

- End -
梦想是咸鱼
关注一下吧
以上为本篇文章的主要内容,希望大家多提意见,如果喜欢记得点个推荐哦
作者:Maggieq8324
本文版权归作者和博客园共有,欢迎转载,转载时保留原作者和文章地址即可。
原文地址:https://www.cnblogs.com/maggieq8324/p/15264900.html