SoFunction
Updated on 2025-04-05

A brief analysis of dynamic components of vue learning record

Dynamic Components

Definition: A method for dynamic switching between components at runtime. Multiple conditional components can be usedv-ifv-else-ifv-elseSwitched components) simplified into one line of code

See an exampleGenerally speaking, we will implement a tabs switch in this way

<template>
  <div >
    <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/";
import cutUp from "./components/";
import Fried  from "./components/";

export default {
  name: "app",
  components: {
    Buy,
    cutUp,
    Fried,
  },
  created() {},
  data() {
    return {
      tabs: ["Buy", "cutUp", "Fried"],
      index:'Buy'
    };
  },
  methods: {
    onClickTabs(item){

      (item,9999);
      =item
    }
  },
};
</script>
<style lang="scss" scoped>
</style>

Dynamic component form can be written as

<template>
  <div >
    <button v-for="item in tabs" :key="item" @click="onClickTabs(item)">{{item}}</button>
    <component :is="index"></component>
  </div>
</template>

<script>
import Buy from "./components/";
import cutUp from "./components/";
import Fried  from "./components/";

export default {
  name: "app",
  components: {
    Buy,
    cutUp,
    Fried,
  },
  created() {},
  data() {
    return {
      tabs: ["Buy", "cutUp", "Fried"],
      index:'Buy'
    };
  },

  methods: {
    onClickTabs(item){
      (item,9999);
      =item
    }
  },
};
</script>
<style lang="scss" scoped>
</style>

In the above example,v-ifAdd-on name iscomponentsaddisReplaced. As for the others, there are not many differences. Thedatapassdata, the transmission state is transmitted.

Supplement: Dynamically calling component example

<div >
<button @click="changeComponent('coma')">coma</button>
<button @click="changeComponent('comb')">comb</button>
<button @click="changeComponent('comc')">comc</button>
 
<component :is="com_name"></component>
</div>
 
<script>
var coma = {
template: '<div>aaaa</div>'
}
var comb = {
template: '<div>bbbb</div>'
}
var comc = {
template: '<div>cccc</div>'
}
let vm = new Vue({
el: '#app',
data: {
com_name: 'coma'
},
components: {
coma: coma,
comb: comb,
comc: comc,
},
methods: {
changeComponent: function(name) {
this.com_name = name
}
}
})
</script>

Summarize

This is the end of this article about the dynamic components of vue learning records. For more related content of vue dynamic components, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!