动态组件

释义:运行时在组件之间动态切换的方法。可以将多个条件组件(使用v-ifv-else-ifv-else切换的组件)简化为一行代码

看个比如
一般来讲,我们会这样实现一个tabs的切换

<template>
  <div id="app">
    <button v-for="item in tabs" :key="item" @click="onClickTabs(item)">{{item}}</button>
    <Buy v-if="index==='Buy'"/>
    <cutUp v-else-if="index==='cutUp'"/>
    <Fried v-else/>
  </div>
</template>
<script>
import Buy from "./components/Buy.vue";
import cutUp from "./components/cutUp.vue";
import Fried  from "./components/Fried.vue";
export default {
  name: "app",
  components: {
    Buy,
    cutUp,
    Fried,
  },
  created() {},
  data() {
    return {
      tabs: ["Buy", "cutUp", "Fried"],
      index:'Buy'
    };
  },
  methods: {
    onClickTabs(item){
      console.log(item,9999);
      this.index=item
    }
  },
};
</script>
<style lang="scss" scoped>
</style>

而动态组件形式则可以写成

<template>
  <div id="app">
    <button v-for="item in tabs" :key="item" @click="onClickTabs(item)">{{item}}</button>
    <component :is="index"></component>
  </div>
</template>
<script>
import Buy from "./components/Buy.vue";
import cutUp from "./components/cutUp.vue";
import Fried  from "./components/Fried.vue";
export default {
  name: "app",
  components: {
    Buy,
    cutUp,
    Fried,
  },
  created() {},
  data() {
    return {
      tabs: ["Buy", "cutUp", "Fried"],
      index:'Buy'
    };
  },
  methods: {
    onClickTabs(item){
      console.log(item,9999);
      this.index=item
    }
  },
};
</script>
<style lang="scss" scoped>
</style>

在以上比如中,v-if加组件名被componentsis替换掉了。至于其他,则没太多分别。该传datadata,该传状况传状况。