vue3使用component :is 加载组件或者切换组件

357 阅读1分钟

1.方法一:使用setup语法糖,is必须使用组件实例,不可以使用字符串

<script setup>
import HelloWorld from './components/HelloWorld.vue'
import HelloWorld2 from './components/HelloWorld2.vue'
import {reactive, ref, shallowRef} from 'vue'

// 使用ref切换不了,如果使用 markRaw 那么currentComp将不永远不会再成为响应式对象。 所以得使用 shallowRef
const tabComponent = shallowRef(HelloWorld)
const changeHandle = () => {
  tabComponent.value = tabComponent.value === HelloWorld ? HelloWorld2 : HelloWorld
  console.log(tabComponent.value)
}
</script>

<template>
  <header>
    <div class="wrapper">
      <!-- 使用 <component> 标签动态渲染组件 -->
      <component :is="tabComponent"></component>
      <!-- 绑定点击事件到 changeHandle 方法 -->
      <button @click="changeHandle">切换</button>
    </div>
  </header>
</template>

2.方法二:使用setup语法糖,is必须使用组件实例,不可以使用字符串

<script setup>
import HelloWorld from './components/HelloWorld.vue'
import HelloWorld2 from './components/HelloWorld2.vue'
import {ref} from 'vue'

const flag = ref(true)

</script>

<template>
  <header>
    <div class="wrapper">
      <!-- 使用 <component> 标签动态渲染组件 -->
      <component :is="flag?HelloWorld:HelloWorld2"></component>
      <!-- 绑定点击事件到 changeHandle 方法 -->
      <button @click="flag=!flag">切换</button>
    </div>
  </header>
</template>

3.不使用setup语法糖的方式和vue2差不多,is可以是个字符串

<script>
import HelloWorld from './components/HelloWorld.vue'
import HelloWorld2 from './components/HelloWorld2.vue'

export default {
  components:{
    HelloWorld,
    HelloWorld2
  },
  data(){
    return{
      tabComponent:"HelloWorld"
    }
  },
  methods:{
    changeHandle(){
      this.tabComponent = this.tabComponent === "HelloWorld" ? "HelloWorld2" : "HelloWorld"
      console.log(this.tabComponent)
    }
  }
}
</script>

<template>
  <header>
    <div class="wrapper">
      <!-- 使用 <component> 标签动态渲染组件 -->
      <component :is="tabComponent"></component>
      <!-- 绑定点击事件到 changeHandle 方法 -->
      <button @click="changeHandle">切换</button>
    </div>
  </header>
</template>