如何动态加载VueJS组件的模板?

时间:2019-10-23 08:14:03

标签: javascript vue.js

我想动态加载VueJS组件的模板,

我尝试了以下代码:

<template>
  <div>

    <default></default>
    <div v-component="{currentView}"></div>
  </div>
</template>

<script>
import { Component, Vue, Watch } from "vue-property-decorator";
//import App from './App.vue'
import VueFormWizard from "vue-form-wizard";

@Component({})
export default class detail extends Vue {}

window.addEventListener("load", () => {
  window.onload = function() {
    //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>
<style>
textarea {
  width: 100%;
  min-height: 100px;
}
</style>

但我收到错误消息:

  

[Vue警告]:属性或方法“ currentView”未在   实例,但在渲染过程中被引用。确保此属性是   在data选项中或对于基于类的组件,通过   初始化属性。看到:   https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties

我该如何解决?

0 个答案:

没有答案