component 动态组件 和 is属性

何为动态组件?

动态组件:多个组件使用同一个挂载点,并动态切换
必要条件:
组件标签使用:

  1. <component></component>

动态绑定使用 is 特性 v-bind:is=””

  1. <div id="main">
  2. <button @click="changeCom('home')">Home</button>
  3. <button @click="changeCom('page')">page</button>
  4. <button @click="changeCom('about')">About</button>
  5. <component :is="variable"></component>
  6. </div>
  1. const vm = new Vue({
  2. el: "#app",
  3. components: {
  4. home: {template: `<div>home</div>`},
  5. page: {template: `<div>page</div>`},
  6. about: {template: `<div>about</div>`},
  7. },
  8. data: {
  9. variable: 'home'
  10. },
  11. methods: {
  12. changeCom(name) {
  13. this.variable = name
  14. }
  15. }
  16. })

is 绑定组件的是组件name属性值,也可以绑定一个组件的构造器选项对象

  1. <component :is="comOptions"></component>
  1. data: {
  2. comOptions: {
  3. template: `<div>直接传入一个组件的选项对象</div>`,
  4. }
  5. }
  1. <template>
  2. <div class="box">
  3. <button @click="com='parent'">parent显示</button>
  4. <button @click="com = 'person'">person显示</button>
  5. <component :is="com"></component>
  6. </div>
  7. </template>
  8. <script>
  9. import MyParent from './components/MyParent.vue'
  10. import MyPerson from './components/myPerson.vue'
  11. export default {
  12. components: {
  13. parent: MyParent,
  14. person: MyPerson,
  15. },
  16. data() {
  17. return {
  18. com: 'person',
  19. }
  20. }
  21. }
  22. </script>
  23. <style scoped>
  24. .box {
  25. padding: 50px;
  26. background: pink;
  27. border: 5px solid orchid;
  28. }
  29. </style>