javascript - vue2.0动态添加组件
迷茫
迷茫 2017-04-11 13:23:08
[JavaScript讨论组]

如何做到点击一个按钮动态添加一个组件呢?
是.vue组件

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回复(3)
天蓬老师

我是写在父组件中的:

Vue.component('mycontent', {
        props: ['content'],
        data() {
            return {
                coms: [],
            }
        },
        render: function(h) {
            this.coms = [];
            for(var i = 0; i < this.content.length; i++) {
                this.coms.push(h(this.content[i], {}))
            }
            return h('p', {},
                this.coms)
        },
    });

调用的时候


    <mycontent v-bind:content="content"></mycontent>

那么父组件中的content变化时,就会动态加载组件了

黄舟
<template>
    <input type="text" v-model='componentName'>
    <button @click='add'>click me to add a component</button>
</template>

<script>
    // 引入要添加的所有组件
    import component1 from './components/component1.vue'
    import component2 from './components/component2.vue'
    export default {
        data: function() {
            return {
                allComponents: [],
                componentName: ''
            }
        },
        components: {
                // 注册所有组件
                component1,
                component2
        }
        methods: {
            add: function() {
                this.allComponents.push(this.componentName)
                // 重置输入框
                this.componentName = ''
            },
            render: function(h) { // h 为 createElement 函数,接受三个参数
                // tag 
                // data
                // children 具体看文档吧
                return h('p',this.allComponents.map(function(componentName) {
                    return h(componentName)
                }))
            }
        }
    }
</script>
伊谢尔伦

更改data
遍历data动态渲染component 就好了 ~~

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号