vue中动态组件

曾经终败给现在 2022-12-17 07:29 315阅读 0赞

有的时候,在不同组件之间进行动态切换是非常有用的,比如在一个多标签的界面里:效果如下

2020102319164871.gif

灰色的两个按钮A,B 用于切换组件,红色边框和蓝色边框的是具体组件的样子;

具体代码:

组件A:

  1. <template>
  2. <div style="width:80px;height:60px;border:1px solid red;margin: 0 auto;">组件A</div>
  3. </template>
  4. <script>
  5. export default {
  6. name: "compa",
  7. data() {
  8. return {};
  9. },
  10. methods: {},
  11. };
  12. </script>
  13. <style lang="less" scoped>
  14. </style>

组件B类似,只是style的宽高等不一致;

父组件代码:

  1. <template>
  2. <div>
  3. <component :is="currentView"></component>
  4. <button @click="handleChangeView('compa')">A</button>
  5. <button @click="handleChangeView('compb')">B</button>
  6. </div>
  7. </template>
  8. <script>
  9. import compa from "./compA.vue";
  10. import compb from "./compB.vue";
  11. export default {
  12. name: "Table",
  13. components: { compa, compb, },
  14. data() {
  15. return {
  16. currentView: "compa",
  17. };
  18. },
  19. methods: {
  20. handleChangeView(component) {
  21. this.currentView = component;
  22. },
  23. },
  24. };
  25. </script>

说明:组件切换主要是通过 Vue 的 <component> 元素加一个特殊的 is attribute 来实现:

发表评论

表情:
评论列表 (有 0 条评论,315人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Vue 动态组件

    动态组件 通过使用保留的 <component> 元素,并对其 is 特性进行动态绑定,你可以在同一个挂载点动态切换多个组件: var vm = new Vue

    相关 Vue动态组件

    Vue动态组件 1、序言 2、实例 1、序言   在页面应用程序中,经常会遇到多标签页面,在Vue.js中,可以通过动态组件来实现。组件的动态切换是通