为什么动态挂载的 vuejs 内容不是根 vue 实例的子组件? [英] why dynamically mounted vuejs content is not child component of root vue instance?

查看:21
本文介绍了为什么动态挂载的 vuejs 内容不是根 vue 实例的子组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我加载了一些包含自定义组件的 html,并将该内容挂载到父组件中的固定节点.不幸的是,我发现它们之间没有父子关系,因此动态插入组件调度的事件无法被root vue接收.我已经创建了一个小提琴,任何帮助或建议表示赞赏!http://jsfiddle.net/matiascx/7Ljygv81/1/

<button v-on="click: addNewElement()">添加自定义元素</button><br/><div id="动态加载"></div>

JS:

new Vue({el: '#app',数据: {sampleElement: '<div class="dynamic-child"><button v-on="click: test()">Test</button></div>'},方法:{添加新元素:函数(){var vmtemp = Vue.extend({模板:this.sampleElement,方法: {测试:函数(){alert("来自动态加载的内容");this.$dispatch('child-msg','this来自ajax加载的组件');}}});new vmtemp().$mount(document.getElementById('dynamicloaded'));},测试:函数(){警报('测试');},事件:{'子味精':函数(味精){console.log('收到消息'+msg);}}}});

解决方案

感谢 vuejs creator 的帮助,我尝试了异步组件方法,当动态内容渲染到 dom 后,它确实有效并且正确的父子关系设置.https://github.com/vuejs/vue/issues/3255#issuecomment-231686976

I load some html containing customized component, and mount that content to a fixed node in parent component. Unfortunately, i found there is no parent-child relationship between them, so the events dispatched by dynamically inserted component can not be received by root vue. I have created one fiddle, any help or proposal is appreciated!. http://jsfiddle.net/matiascx/7Ljygv81/1/

<div id="app">
    <button v-on="click: addNewElement()">Add custom Element</button> 
    <br />
    <div id="dynamicloaded"></div>
</div>

JS:

new Vue({
    el: '#app',
    data: {
        sampleElement: '<div class="dynamic-child"><button v-on="click: test()">Test</button></div>'

    },
    methods:{
        addNewElement: function(){



           var vmtemp = Vue.extend({
                            template: this.sampleElement,
                            methods: {
                             test: function(){
                               alert("comes from dynamically loaded content");
                               this.$dispatch('child-msg','this comes from ajax loaded component');
                             }
                            }
                        });
           new vmtemp().$mount(document.getElementById('dynamicloaded'));
        },
        test: function(){
           alert('Test');
        },
        events: {
         'child-msg': function(msg){
            console.log('message received'+msg);
         }
        }
    }
});

解决方案

thanks to the vuejs creator's help, i have tried async component approach, it really works and right parent-child relationship setup when after dynamic content rendered into dom. https://github.com/vuejs/vue/issues/3255#issuecomment-231686976

这篇关于为什么动态挂载的 vuejs 内容不是根 vue 实例的子组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆