vue tab组件_Vue.js从零开始——组件(5)

51a8175b0179e412e5f55cc84e2e05e1.png

今天回过头来看在 Hofbräuhaus Müchen (慕尼黑皇家啤酒馆) 拍的照片,才感觉有意思,这个地方把周边都做得特别好,明明是饭店,居然还卖衣服、绘本、文具、地图指南等等,真的是因为自己是地标,也是慕尼黑最有代表性的啤酒品牌,所以旅游热点这份钱也赚起来啦,哈哈。

对了,这也是当时我们去过的两家有中文菜单的其中之一。

又扯远了,今天这一章节的重点是动态和异步组件。


1 动态组件

1.1 概念

有的时候,在不同组件之间进行动态切换是非常有用的,比如下面是官网的一个多标签的界面(这里没有声明 Vue 实例变量,是因为页面上仅有一个实例,之后的演示也会这样处理):

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>hello</title>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <style>
      .dynamic-component-demo-tab-button {
        padding: 6px 10px;
        border-top-left-radius: 3px;
        border-top-right-radius: 3px;
        border: 1px solid #ccc;
        cursor: pointer;
        background: #f0f0f0;
        margin-bottom: -1px;
        margin-right: -1px;
      }
      .dynamic-component-demo-tab-button:hover {
        background: #e0e0e0;
      }
      .dynamic-component-demo-tab-button-active {
        background: #e0e0e0;
      }
      .dynamic-component-demo-tab {
        border: 1px solid #ccc;
        padding: 10px;
      }
    </style>
  </head>
  <body>
    <div id="dynamic-component-demo" class="demo">
      <button
        v-for="tab in tabs" 
        :key="tab" class="dynamic-component-demo-tab-button" 
        :class="{ 'dynamic-component-demo-tab-button-active': tab === currentTab }" 
        @click="currentTab = tab">
        {{ tab }}
      </button>
      <component 
        :is="currentTabComponent" 
        class="dynamic-component-demo-tab">
      </component>
    </div>
    <script>
    Vue.component('tab-home', { template: '<div>Home component</div>' });
    Vue.component('tab-posts', { template: '<div>Posts component</div>' });
    Vue.component('tab-archive', { template: '<div>Archive component</div>' });
    new Vue({
      el: '#dynamic-component-demo',
      data: {
        currentTab: 'Home',
        tabs: ['Home', 'Posts', 'Archive']
      },
      computed: {
        currentTabComponent: function () {
          return 'tab-' + this.currentTab.toLowerCase();
        }
      }
    });
    </script>
  </body>
</html>

107c25963892f43999bc1e99062a9546.gif

上述内容可以通过 Vue<component> 元素加一个特殊的 is 属性来实现:

<!-- 组件会在 currentTabComponent 改变时改变 -->
<component :is="currentTabComponent"></component>

在上述示例中,currentTabComponent 可以包括:

  • 已注册组件的名字
  • 一个组件的选项对象

官网的这个版本里,我们可以看到绑定组件选项对象,而不是已注册组件名的示例。

请留意,这个属性可以用于常规 HTML 元素,但这些元素将被视为组件,这意味着所有的属性都会作为 DOM 属性被绑定;对于像 value 这样的属性,若想让其如预期般工作,我们需要使用 .prop 修饰器

虽然中文都翻译成属性,但在英文当中,propertyattribute 是不同的,首先 property 是由 DOM 定义的属性,而 attribute 是由 HTML 定义的属性,两者之间往往不是一一相互对应的关系,value 虽然在两者当中都存在,但 HTML 属性中的 value 是不会更改的,而 DOM 属性的 value 会随内容改变而更改,打个比方:

<input id="test" value="Michael"> 当中,如果我在输入框当中修改为 Benjamin,此时 HTML 属性的 value 当中的值仍然是 Michael,而 DOM 属性中 value 的值已经改为 Benjamin 了,如下图:

9b099010bdf890609e1b9f9b5db0ad20.gif

这也是为什么要特意强调 value 这个属性的特殊性,并为此增设了一个 .prop 修饰符。

1.2 保持组件状态

我们上面在多标签的界面中使用 is 属性来切换不同的组件:

<component :is="currentTabComponent"></component>

当在这些组件之间切换的时候,有些情况下会想保持这些组件的状态,以避免反复重渲染导致的性能问题,例如我们来展开说一说下面这个多标签界面:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>hello</title>
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    <style>
      .dynamic-component-demo-tab-button {
        padding: 6px 10px;
        border-top-left-radius: 3px;
        border-top-right-radius: 3px;
        border: 1px solid #ccc;
        cursor: pointer;
        background: #f0f0f0;
        margin-bottom: -1px;
        margin-right: -1px;
      }
      .dynamic-component-demo-tab-button:hover {
        background: #e0e0e0;
      }
      .dynamic-component-demo-tab-button.dynamic-component-demo-active {
        background: #e0e0e0;
      }
      .dynamic-component-demo-tab {
        border: 1px solid #ccc;
        padding: 10px;
      }
      .dynamic-component-demo-posts-tab {
        display: flex;
      }
      .dynamic-component-demo-posts-sidebar {
        max-width: 40vw;
        margin: 0 !important;
        padding: 0 10px 0 0 !important;
        list-style-type: none;
        border-right: 1px solid #ccc;
      }
      .dynamic-component-demo-posts-sidebar li {
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        cursor: pointer;
      }
      .dynamic-component-demo-posts-sidebar li:hover {
        background: #eee;
      }
      .dynamic-component-demo-posts-sidebar li.dynamic-component-demo-active {
        background: lightblue;
      }
      .dynamic-component-demo-post-container {
        padding-left: 10px;
      }
      .dynamic-component-demo-post > :first-child {
        margin-top: 0 !important;
        padding-top: 0 !important;
      }
    </style>
  </head>
  <body>
    <div id="dynamic-component-demo" class="demo">
      <button
        v-for="tab in tabs" 
        :key="tab" 
        :class="['dynamic-component-demo-tab-button', { 'dynamic-component-demo-active': currentTab === tab }]" 
        @click="currentTab = tab">
        {{ tab }}
      </button>
      <component 
        :is="currentTabComponent" 
        class="dynamic-component-demo-tab">
      </component>
    </div>
    <script>
    Vue.component('tab-posts', {
      data: function () {
        return {
          posts: [
            {
              id: 1,
              title: 'Cat Ipsum',
              content: '<p>Dont wait for the storm to pass, dance in the rain kick up litter decide to want nothing to do with my owner today demand to be let outside at once, and expect owner to wait for me as i think about it cat cat moo moo lick ears lick paws so make meme, make cute face but lick the other cats. Kitty poochy chase imaginary bugs, but stand in front of the computer screen. Sweet beast cat dog hate mouse eat string barf pillow no baths hate everything stare at guinea pigs. My left donut is missing, as is my right loved it, hated it, loved it, hated it scoot butt on the rug cat not kitten around</p>'
            },
            {
              id: 2,
              title: 'Hipster Ipsum',
              content: '<p>Bushwick blue bottle scenester helvetica ugh, meh four loko. Put a bird on it lumbersexual franzen shabby chic, street art knausgaard trust fund shaman scenester live-edge mixtape taxidermy viral yuccie succulents. Keytar poke bicycle rights, crucifix street art neutra air plant PBR&B hoodie plaid venmo. Tilde swag art party fanny pack vinyl letterpress venmo jean shorts offal mumblecore. Vice blog gentrify mlkshk tattooed occupy snackwave, hoodie craft beer next level migas 8-bit chartreuse. Trust fund food truck drinking vinegar gochujang.</p>'
            },
            {
              id: 3,
              title: 'Cupcake Ipsum',
              content: '<p>Icing dessert soufflé lollipop chocolate bar sweet tart cake chupa chups. Soufflé marzipan jelly beans croissant toffee marzipan cupcake icing fruitcake. Muffin cake pudding soufflé wafer jelly bear claw sesame snaps marshmallow. Marzipan soufflé croissant lemon drops gingerbread sugar plum lemon drops apple pie gummies. Sweet roll donut oat cake toffee cake. Liquorice candy macaroon toffee cookie marzipan.</p>'
            }
          ],
          selectedPost: null
        }
      },
      template: `
        <div class="dynamic-component-demo-posts-tab">
          <ul class="dynamic-component-demo-posts-sidebar">
            <li
              v-for="post in posts"
              v-bind:key="post.id"
              v-bind:class="{ 'dynamic-component-demo-active': post === selectedPost }"
              v-on:click="selectedPost = post"
            >
              {{ post.title }}
            </li>
          </ul>
          <div class="dynamic-component-demo-post-container">
            <div 
              v-if="selectedPost"
              class="dynamic-component-demo-post"
            >
              <h3>{{ selectedPost.title }}</h3>
              <div v-html="selectedPost.content"></div>
            </div>
            <strong v-else>
              Click on a blog title to the left to view it.
            </strong>
          </div>
        </div>
      `
    });
    Vue.component('tab-archive', {
      template: '<div>Archive component</div>'
    });
    new Vue({
      el: '#dynamic-component-demo',
      data: {
        currentTab: 'Posts',
        tabs: ['Posts', 'Archive']
      },
      computed: {
        currentTabComponent: function () {
          return 'tab-' + this.currentTab.toLowerCase();
        }
      }
    });
    </script>
    
  </body>
</html>

1b4720fb5ad185d970b717c767321f4b.gif

我们可以注意到,如果选择了一篇文章,切换到 Archive 标签,然后再切换回 Posts,是不会继续展示之前选择的文章的;这是因为每次切换新标签的时候,Vue 都创建了一个新的 currentTabComponent 实例。

重新创建动态组件的行为通常是非常有用的,但是在这个案例中,我们更希望那些标签的组件实例能够被在它们第一次被创建的时候缓存下来,为了解决这个问题,我们可以用一个 <keep-alive> 元素将其动态组件包裹起来:

<!-- 失活的组件将会被缓存!-->
<keep-alive>
  <component :is="currentTabComponent"></component>
</keep-alive>

来看看修改后的结果:

71b7bce01124f0516aeb397812ed3cd4.gif

现在这个 Posts 标签保持了它的状态(被选中的文章)甚至当切换到其他标签的时候(未被渲染)也是如此;完整代码就不附上了,在本节开始的例子中 <component> 元素外加上 <keep-alive> 即可。

更多的信息可以参考官方文档:API — Vue.js

注意这个 <keep-alive> 要求被切换到的组件都有自己的名字,不论是通过组件的 name 选项还是局部/全局注册。

2 异步组件

2.1 概念

在大型应用中,我们可能需要将应用分割成小一些的代码块,并且只在需要的时候才从服务器加载一个模块,从而降低客户端访问下载的流量。

为了简化,Vue 允许我们以一个工厂函数的方式定义组件,这个工厂函数会异步解析组件的定义;Vue 只有在这个组件需要被渲染的时候才会触发该工厂函数,且会把结果缓存起来供未来重渲染,例如:

Vue.component('async-example', function (resolve, reject) {
  setTimeout(function () {
    // 向 resolve 回调传递组件定义
    resolve({
      template: '<div>I am async!</div>'
    })
  }, 1000);
});

上面的代码中,这个工厂函数会收到一个 resolve 回调,这个回调函数会在从服务器得到组件定义的时候被调用;我们也可以调用 reject(reason) 来表示加载失败,这里的 setTimeout 是为了演示用的,如何获取组件取决于自己。

一个推荐的做法是将异步组件和 ="https://webpack.http://js.org/guides/code-splitting/">webpack 的 code-splitting 功能一起配合使用:

Vue.component('async-webpack-example', function (resolve) {
  // 这个特殊的 require 语法将会告诉 webpack 自动将你的构建代码切割成多个包,
  // 这些包会通过 Ajax 请求加载
  require(['./my-async-component'], resolve);
});

也可以在工厂函数中返回一个 Promise,所以把 webpack 2 ES 6 语法加在一起,我们可以这样使用动态导入:

Vue.component(
  'async-webpack-example',
  // 这个动态导入会返回一个 Promise 对象。
  () => import('./my-async-component');
);

当使用局部注册的时候,也可以直接提供一个返回 Promise 的函数:

new Vue({
  // ...
  components: {
    'my-component': () => import('./my-async-component');
  }
});

如果是一个 Browserify 用户同时喜欢使用异步组件,很不幸这个工具的作者明确表示异步加载“并不会被 Browserify 支持”,至少官方不会;Browserify 社区已经找到了一些变通方案,这些方案可能会对已存在的复杂应用有帮助。

对于其它的场景,官方推荐直接使用 webpack;我个人会倾向使用 ES 6 的原生语法。

2.2 处理加载的状态

这里的异步组件工厂函数也可以返回一个如下格式的对象:

const AsyncComponent = () => ({
  // 需要加载的组件 (应该是一个 Promise 对象)
  component: import('./MyComponent.vue'),
  // 异步组件加载时使用的组件
  loading: LoadingComponent,
  // 加载失败时使用的组件
  error: ErrorComponent,
  // 展示加载时组件的延时时间。默认值是 200 (毫秒)
  delay: 200,
  // 如果提供了超时时间且组件加载也超时了,
  // 则使用加载失败时使用的组件。默认值是:Infinity
  timeout: 3000
});

此时,组件状态就将通过该对象所定义的内容进行处理了,也方便了喜欢使用原生 JavaScript 语法的开发者(譬如我)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值