在vue.js中渲染动态组件?

时间:2016-11-14 20:49:42

标签: javascript vue-component vue.js

我试图通过使用set timeout伪造ajax调用来渲染vue.js中的动态组件。它应该注册一个新组件,然后在视图中设置它!我正在使用vue.js 1.请告诉我如何解决这个问题的解决方案。



<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>test dynamic components</title>
</head>
<body>
	
	<div v-component="{{currentView}}"></div>


	<script src="vue-v1.js"></script>
	<script>
    //Create the 'default' component
    Vue.component("default", {
        template: '<div>This should be replaced (and will be in 2 seconds)</div>'
    });

    //Create the parent ViewModel
    var vm = new Vue({
        el: "body",
        data: {
            currentView: "default"
        }
    });

    //Pretend to load the data from the server
    //This would actually be $.get("/url", data, function(){...});
    window.setTimeout(function () {
        
        //Create the new component using the template we received
        Vue.component("BoardFeed", {
            template: '<div>Template returned from server, what I really want</div><br>And directives work too:<div v-repeat="items">{{$value}}</div>',
            data: function () {
                return {
                    items: [1, 2, 3]
                };
            }
        });
        
        //And then change the page to that component
        vm.currentView = "BoardFeed";
    }, 2000);
	</script>
</body>
</html>
&#13;
&#13;
&#13;

ISSUE:

我正在使用Vue.js 1而我无法插入我的组件的视图!我不认为使用v-component甚至已经使用了

1 个答案:

答案 0 :(得分:1)

当您进行两处小改动时,您的代码可以正常使用Vue.js:

  1. 使用<component :is="currentView"></component>包含组件。很久以前0.12.0已删除v-component

  2. 使用<div v-for="value in items">{{value}}</div>迭代数组。 1.0已弃用v-repeat

  3. 这是一个有效的JSFiddle