vue学习记录之动态组件浅析
目录
- 动态组件
- 补充:动态调用组件示例
- 总结
动态组件
释义:运行时在组件之间动态切换的方法。可以将多个条件组件(使用
v-if
、v-else-if
、v-else
切换的组件)简化为一行代码
看个例子 一般来讲,我们会这样实现一个tabs的切换
<template> <div id="app"> <button v-for="item in tabs" :key="item" @click="onClickTabs(item)">{{item}}</button> <Buy v-if="index==='Buy'"/> <cutUp v-else-if="index==='cutUp'"/> <Fried v-else/> </div> </template> <script> import Buy from "./components/Buy.vue"; import cutUp from "./components/cutUp.vue"; import Fried from "./components/Fried.vue"; export default { name: "app", components: { Buy, cutUp, Fried, }, created() {}, data() { return { tabs: ["Buy", "cutUp", "Fried"], index:'Buy' }; }, methods: { onClickTabs(item){ console.log(item,9999); this.index=item } }, }; </script> <style lang="scss" scoped> </style>
而动态组件形式则可以写成
<template> <div id="app"> <button v-for="item in tabs" :key="item" @click="onClickTabs(item)">{{item}}</button> <component :is="index"></component> </div> </template> <script> import Buy from "./components/Buy.vue"; import cutUp from "./components/cutUp.vue"; import Fried from "./components/Fried.vue"; export default { name: "app", components: { Buy, cutUp, Fried, }, created() {}, data() { return { tabs: ["Buy", "cutUp", "Fried"], index:'Buy' }; }, methods: { onClickTabs(item){ console.log(item,9999); this.index=item } }, }; </script> <style lang="scss" scoped> </style>
在以上例子中,
v-if
加组件名被components
加is
替换掉了。至于其他,则没太多分别。该传data
传data
,该传状态传状态。
补充:动态调用组件示例
<div id="app"> <button @click="changeComponent('coma')">coma</button> <button @click="changeComponent('comb')">comb</button> <button @click="changeComponent('comc')">comc</button> <component :is="com_name"></component> </div> <script> var coma = { template: '<div>aaaa</div>' } var comb = { template: '<div>bbbb</div>' } var comc = { template: '<div>cccc</div>' } let vm = new Vue({ el: '#app', data: { com_name: 'coma' }, components: { coma: coma, comb: comb, comc: comc, }, methods: { changeComponent: function(name) { this.com_name = name } } }) </script>
总结
到此这篇关于vue学习记录之动态组件的文章就介绍到这了,更多相关vue动态组件内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!
赞 (0)