组件并不老是具有雷同的构造。偶然须要治理很多差别的状况。异步实行此操纵会很有协助。
实例:
组件模板某些网页中用于多个位置,比方关照,解释和附件。让我们来一同看一下批评,看一下我表达的意义是什么。
批评如今不再仅仅是简朴的文本字段。您愿望能够宣布链接,上传图象,集成视频等等。必需在此解释中显现一切这些完整差别的元素。假如你试图在一个组件内实行此操纵,它很快就会变得异常杂沓。
处置惩罚方式
我们该怎样处置惩罚这个题目?能够大多数人会先搜检一切状况,然后在此之后加载特定组件。像如许的东西:
<template>
<div class="comment">
// comment text
<p>...</p>
// open graph image
<link-open-graph v-if="link.type === 'open-graph'" />
// regular image
<link-image v-else-if="link.type === 'image'" />
// video embed
<link-video v-else-if="link.type === 'video'" />
...
</div>
</template>
然则,假如支撑的模板列表变得越来越长,这能够会变得异常杂沓和反复。在我们的批评案例中 – 只想到支撑Youtube,Twitter,Github,Soundcloud,Vimeo,Figma的嵌入……这个列表是无止境的。
动态组件模板
另一种方法是运用某种加载器来加载您须要的模板。这许可你编写一个像如许的清洁组件:
<template>
<div class="comment">
// comment text
<p>...</p>
// type can be 'open-graph', 'image', 'video'...
<dynamic-link :data="someData" :type="type" />
</div>
</template>
看起来好多了,不是吗?让我们看看这个组件是怎样事情的。起首,我们必需变动模板的文件夹构造。
就个人而言,我喜好为每一个组件建立一个文件夹,由于能够在今后增加更多用于款式和测试的文件。固然,您愿望怎样构建构造取决于你本身。
接下来,我们来看看怎样<dynamic-link />构建此组件。
<template>
<component :is="component" :data="data" v-if="component" />
</template>
<script>
export default {
name: 'dynamic-link',
props: ['data', 'type'],
data() {
return {
component: null,
}
},
computed: {
loader() {
if (!this.type) {
return null
}
return () => import(`templates/${this.type}`)
},
},
mounted() {
this.loader()
.then(() => {
this.component = () => this.loader()
})
.catch(() => {
this.component = () => import('templates/default')
})
},
}
</script>
那末这里发作了什么?默许状况下,Vue.js支撑动态组件。题目是您必需注册/导入要运用的一切组件。
<template>
<component :is="someComponent"></component>
</template>
<script>
import someComponent from './someComponent'
export default {
components: {
someComponent,
},
}
</script>
这里没有任何东西,由于我们想要动态地运用我们的组件。所以我们能够做的是运用Webpack的动态导入。与盘算值一同运用时,这就是把戏发作的处所 – 是的,盘算值能够返回一个函数。超等轻易!
computed: {
loader() {
if (!this.type) {
return null
}
return () => import(`templates/${this.type}`)
},
},
装置我们的组件后,我们尝试加载模板。假如出现题目我们能够设置后备模板。或许这对向用户显现毛病音讯很有协助。
mounted() {
this.loader()
.then(() => {
this.component = () => this.loader()
})
.catch(() => {
this.component = () => import('templates/default')
})
},
结论
假如您有一个组件的很多差别视图,则能够很有效。
- 易于扩大。
- 它是异步的。模板仅在须要时加载。
- 坚持代码清洁。
基本上就是如许!
假如你已运用过这类手艺,我很想听听你的看法,感谢!