第二十八篇 vue - 深入组件 - 动态组件 - component

发布时间 2023-04-01 11:49:25作者: caix-1987

component

动态组件就是动态变化的组件,和动态样式一样,通过用户的操作来确定是什么类型的组件。动态样式是绑定:style,动态组件则是绑定:is

在 vue 中,实现 Tab 切换主要有三种方式:使用动态组件,使用 vue-router 路由,使用第三方插件。本文将详细介绍Vue动态组件

所谓动态组件就是让多个组件使用同一个挂载点,并动态切换

vue内置component组件, 配合is属性, 设置要显示的组件标签名字

is 用法

通过使用保留的 <component> 元素,动态地绑定到它的 is 特性,我们让多个组件可以使用同一个挂载点,并动态切换

根据 v-bind:is="组件名" 中的组件名去自动匹配组件,如果匹配不到则不显示

改变挂载的组件,只需要修改is指令的值即可

注意

 1、is只能是动态属性 :is="组件注册后的标签名字符串或data变量"
 
 2、不能直接拿注册标签名赋值使用
示例
<!DOCTYPE html>
<html>

<head>
  <title>Dynamic Components Example</title>
  <script src="https://unpkg.com/vue"></script>
</head>

<body>
  <div id="example">
    <button @click="change">切换页面</button>
    <component :is="currentView"></component>
  </div>

  <script>
    const home = {
      template: '<div>我是主页</div>'
    };
    const detail = {
      template: '<div>我是详情页</div>'
    };
    const archive = {
      template: '<div>我是存档页</div>'
    };
    new Vue({
      el: '#example',
      components: {
        home,
        detail,
        archive,
      },
      data: {
        index: 0,
        arr: ['home', 'detail', 'archive'],
      },
      computed: {
        currentView() {
          return this.arr[this.index];
        }
      },
      methods: {
        change() {
          this.index = (++this.index) % 3;
        }
      }
    })
  </script>
</body>