网站搜索框代码怎么做,自适应网站什么做,云商城在线下单,中国太空网站文章目录 一、前言二、实现三、优化四、总结五、最后 一、前言
在开发中#xff0c;你经常会遇到这么一种情况#xff1a;根据条件动态地切换某个组件#xff0c;或动态地选择渲染某个组件。 Vue 提供了另外一个内置的组件 component 和 is 特性#xff0c;可以更… 文章目录 一、前言二、实现三、优化四、总结五、最后 一、前言
在开发中你经常会遇到这么一种情况根据条件动态地切换某个组件或动态地选择渲染某个组件。 Vue 提供了另外一个内置的组件 component 和 is 特性可以更好地实现动态组件。
二、实现
首先来看看component 和 is 的基本使用首先定义三个普通组件ABC
templatediv组件 A/div
/template
scriptexport default {}
/scripttemplatediv组件 B/div
/template
scriptexport default {}
/scripttemplatediv组件 C/div
/template
scriptexport default {}
/script然后在父组件中导入这 3 个组件并动态切换
templatedivbutton clickhandleChange(A)显示 A 组件/buttonbutton clickhandleChange(B)显示 B 组件/buttonbutton clickhandleChange(C)显示 C 组件/buttoncomponent :iscomponent/component/div
/template
scriptimport componentA from ../components/a.vue;import componentB from ../components/b.vue;import componentC from ../components/c.vue;export default {data () {return {component: componentA}},methods: {handleChange (component) {if (component A) {this.component componentA;} else if (component B) {this.component componentB;} else if (component C) {this.component componentC;}}}}
/script这里的 is 动态绑定的是一个组件对象Object它直接指向 a / b / c 三个组件中的一个。除了直接绑定一个 Object还可以是一个 String比如标签名、组件名。
下面的这个组件将原生的按钮 button 进行了封装如果传入了 prop: to那它会渲染为一个链接地址 a 标签用于打开这个如果没有传入 to就当作普通 button 使用。
templatecomponent :istagName v-bindtagPropsslot/slot/component
/templatescript
export default {props: {// 链接地址to: {type: String,default: },// 链接打开方式如 _blanktarget: {type: String,default: _self}},computed: {// 动态渲染不同的标签tagName() {return this.to ? button : a},// 如果是链接把这些属性都绑定在 component 上tagProps() {let props {}if (this.to) {props {target: this.target,href: this.to}}return props}}
}
/script使用组件
template
divi-button普通按钮/i-buttonbr /i-button tohttps://juejin.cn链接按钮/i-buttonbr /i-button tohttps://juejin.cn target_blank新窗口打开链接按钮/i-button
/div
/template
script
import iButton from ./components/button.vueexport default {
components: { iButton }
}
/script最终会渲染出一个原生的 button 按钮和两个原生的链接 a且第二个点击会在新窗口中打开链接如图 i-button 组件中的 component is 绑定的就是一个标签名称 button / a并且通过 v-bind 将一些额外的属性全部绑定到了 component 上。
三、优化
再回到第一个 a / b / c 组件切换的示例如果这类的组件频繁切换事实上组件是会重新渲染的。
现在在组件 A 里加两个生命周期 mounted, beforeDestroy。只要切换到 A 组件mounted 就会触发一次切换到其它组件beforeDestroy 也会触发一次说明组件再重新渲染这样有可能导致性能问题。
为了避免组件的重复渲染可以在 component 外层套一个 Vue.js 内置的 keep-alive 组件这样组件就会被缓存起来
keep-alivecomponent :iscomponent/component
/keep-alive这时只有 mounted 触发了如果不离开当前页面切换到其它组件beforeDestroy 不会被触发说明组件已经被缓存了。
四、总结
动态组件广泛应用于灵活渲染组件的场景根据某种条件来渲染不同的组件搭配keep-alive可以避免组件频繁的创建与销毁。
源码地址可点击【跳转】访问在线调试代码
五、最后
本人每篇文章都是一字一句码出来希望对大家有所帮助多提提意见。顺手来个三连击点赞收藏关注✨一起加油☕