vue动态组件和异步组件相关

偶然看见别人代码里component :is的写法,一脸懵逼,故查了相关的一些特性,记录下来,供参考html

Vue动态组件 :is

应用场景:在不一样组件之间进行动态切换
vue

实现:webpack

<!-- 组件会在 `currentTabComponent` 改变时改变 -->
<component v-bind:is="currentTabComponent"></component>复制代码

说明:currentTabComponent 能够包括git

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

demo地址:https://github.com/elainema/elaine/tree/master/VUE/vue-components/src/views/sync-components

查看demo(忽略难看的样式和布局):github

TestComponents.vue:
web

<template><div>    <!-- 按钮,用于切换组件 -->    <button @click="currentTabComponent= 'A'">showA</button>    <button @click="currentTabComponent= 'B'">showB</button>     <!-- 动态切换显隐,组件 -->      <component :is="currentTabComponent"></component></div></template><script>//引入组件A以及组件Bimport A from "./A.vue";import B from "./B.vue";  export default {    data() {      return {        //默认显示组件A,若字符串为B则显示组件B,name在component内声明        showWhat: "A"      };    },    methods: {      handleClick(tab, event) {        console.log(tab, event);      }    },    components: {        //声明组件A,B        A,        B    },    methods:{    }  };</script><style>.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;}.tab-button:hover { background: #e0e0e0;}.tab-button.active { background: #e0e0e0;}.tab { border: 1px solid #ccc; padding: 10px;}.posts-tab { display: flex;}.posts-sidebar { max-width: 40vw; margin: 0; padding: 0 10px 0 0; list-style-type: none; border-right: 1px solid #ccc;}.posts-sidebar li { white-space: nowrap; text-overflow: ellipsis; overflow: hidden; cursor: pointer;}.posts-sidebar li:hover { background: #eee;}.posts-sidebar li.selected { background: lightblue;}.selected-post-container { padding-left: 10px;}.selected-post > :first-child { margin-top: 0; padding-top: 0;}</style>复制代码

A.vue

<template>    <ul class="posts-sidebar">        <li            v-for="post in posts"            v-bind:key="post.id"            v-bind:class="{ selected: post === selectedPost }"            v-on:click="selectedPost = post"        >          {{ post.title }}        </li>      </ul>    </ul></template><script>export default {    name:'A',    data() {        return{            selectedPost: null,            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>'                }            ],        }    }}</script>复制代码

B.vuevue-router

<template><div>        This is component of B</div></template><script>export default {    name:'B',}</script>复制代码

当咱们切换到A,点击某条文章后,切换至B,再切换回A时,并不会展现选中状态,操做步骤见图:api


使用<component v-bind:is="currentTabComponent"></component>,切换的时候每次都会触发生命周期,从新建立动态组件。接下来,咱们为组件A和B加上生命周期,而且断点测试一下:promise

刷新页面,只触发了组件A的生命周期缓存


切换至B(为了看起来方便,我先清除了console),触发了组件B的生命周期


再切换至A(先清除console),再次触发了组件A的生命周期


能够看到,初始化只挂载了组件A,每次切换都会从新触发组件的生命周期,切换时并无保留以前的状态(组件A的选中),可是在在某些状况下,咱们更但愿那些标签的组件实例可以被在它们第一次被建立的时候缓存下来。为了解决这个问题,咱们能够用一个 <keep-alive> 元素将其动态组件包裹起来。

vue生命周期图贴一下:

TestComponents.vue,其余代码不变,只用<keep-alive> 元素将 <component :is="currentTabComponent"></component>包裹起来

<!-- 动态切换显隐,组件 -->     <keep-alive>        <component :is="currentTabComponent"></component>     </keep-alive>复制代码

如今,咱们再次刷新页面,而且选中一条文章


切换至Tab B,能够看到并无销毁组件A


这时候,咱们再次切回至组件A,能够看到,没有从新触发组件A的生命周期,而且保留了组件A文章的选中状态。


深刻了解:https://cn.vuejs.org/v2/guide/components-dynamic-async.html

关于keep-alive的详细api参考:https://cn.vuejs.org/v2/api/#keep-alive

<!-- 失活的组件将会被缓存!-->
<keep-alive>
  <component v-bind:is="currentTabComponent"></component></keep-alive>复制代码

注意这个 <keep-alive> 要求被切换到的组件都有本身的名字,不管是经过组件的 name 选项仍是局部/全局注册。


v-show

demo到这里,咱们来讲一说为何不用 v-show 来切换呢, V-show 会第一时间加载两个组件, 两个组件的生命周期都会触发,会形成没必要要的性能浪费,代码改一下:

<!-- 动态切换显隐,组件 -->     <!-- <keep-alive>        <component :is="currentTabComponent"></component>     </keep-alive> -->     <A v-show="currentTabComponent == 'A'"></A>     <B v-show="currentTabComponent == 'B'"></B>复制代码

刷新页面,能够看到,初始化,组件A和B的生命周期都被触发了,而在切换时并不会从新触发组件的生命,会保留组件A的文章选中状态,若是咱们但愿切换时从新触发组件的生命周期,好比从新发送异步请求获取数据等,则没法实现。


v-if

相信你们都想到了v-if,若是是v-if的话 确实不会形成同时加载两个组件,不过v-if切换的话, 每次都会从新挂载一次,若是没有从新渲染的须要的话 ,会形成性能浪费,代码改一下,看一下效果:

<!-- 动态切换显隐,组件 -->     <!-- <keep-alive>        <component :is="currentTabComponent"></component>     </keep-alive> -->     <A v-if="currentTabComponent == 'A'"></A>     <B v-if="currentTabComponent == 'B'"></B>复制代码


好了,到此 动态组件:is,v-if和v-show的优劣和使用场景大概就这样了~关于:is的具体使用能够结合官网,搜索一下网上的例子,就熟悉了~

异步组件

在大型应用中,咱们可能须要将应用分割成小一些的代码块,而且只在须要的时候才从服务器加载一个模块。为了简化,Vue 容许你以一个工厂函数的方式定义你的组件,这个工厂函数会异步解析你的组件定义。Vue 只有在这个组件须要被渲染的时候才会触发该工厂函数,且会把结果缓存起来供将来重渲染,参考:https://cn.vuejs.org/v2/guide/components-dynamic-async.html#%E5%BC%82%E6%AD%A5%E7%BB%84%E4%BB%B6

1. vue异步组件技术

vue-router配置路由,使用vue的异步组件技术,能够实现按需加载。 可是,这种状况下一个组件生成一个js文件。 举例以下:

{
    path: '/promisedemo',
    name: 'PromiseDemo',
    component: resolve => require(['../components/PromiseDemo'], resolve)
 }复制代码

2. es提案的import()

推荐使用这种方式(须要webpack > 2.4)

参考:https://router.vuejs.org/zh/guide/advanced/lazy-loading.html

vue-router配置路由,代码以下:

// 下面2行代码,没有指定webpackChunkName,每一个组件打包成一个js文件。
const ImportFuncDemo1 = () => import('../components/ImportFuncDemo1')
const ImportFuncDemo2 = () => import('../components/ImportFuncDemo2')
// 下面2行代码,指定了相同的webpackChunkName,会合并打包成一个js文件。
// const ImportFuncDemo = () => import(/* webpackChunkName: 'ImportFuncDemo' */ '../components/ImportFuncDemo')
// const ImportFuncDemo2 = () => import(/* webpackChunkName: 'ImportFuncDemo' */ '../components/ImportFuncDemo2')
export default new Router({
   routes: [
       {
           path: '/importfuncdemo1',
           name: 'ImportFuncDemo1',
           component: ImportFuncDemo1
       },
       {
           path: '/importfuncdemo2',
           name: 'ImportFuncDemo2',
           component: ImportFuncDemo2
       }
   ]
})复制代码

3. webpack提供的require.ensure()

vue-router配置路由,使用webpack的[require.ensure](Module API - Methods)技术,也能够实现按需加载。 这种状况下,多个路由指定相同的chunkName,会合并打包成一个js文件。 举例以下:

{
     path: '/promisedemo',
     name: 'PromiseDemo',
     component: r => require.ensure([], () => r(require('../components/PromiseDemo')), 'demo')
},
{
     path: '/hello',
     name: 'Hello',
     component: r => require.ensure([], () => r(require('../components/Hello')), 'demo')
}复制代码
相关文章
相关标签/搜索