欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Vue异步加载about组件

程序员文章站 2022-04-09 21:19:27
本文实例为大家分享了vue异步加载about组件的具体代码,供大家参考,具体内容如下 异步加载about组件 about.js vue.component('...

本文实例为大家分享了vue异步加载about组件的具体代码,供大家参考,具体内容如下

异步加载about组件

about.js

vue.component('about', {template: '<div>about page</div>'}); 

html代码:

<div id="app">
    <router-link to="/home">/home</router-link>
    <router-link to="/about">/about</router-link>
    <router-view></router-view>
  </div>
  <script src="static/js/vue.min.js"></script>
  <script src="static/js/vue-router.js"></script>
  <script>
    function load (componentname, path) {
      return new promise(function (resolve, reject){
        var script = document.createelement('script');
        script.src = path;
        script.async = true;
        script.onload = function () {
          var component = vue.component(componentname);
          if (component) {
            resolve(component);
          } else {
            reject();
          }
        }
        document.body.appendchild(script);
      });
    }
    var router = new vuerouter({
      routes: [{
        path: '/',
        redirect: '/home'
      }, {
        path: '/home',
        component: {
          template: '<div>home page</div>'
        }
      },{
        path: '/about',
        component: function (resolve, reject) {
          load('about', 'static/js/business/about.js').then(resolve, reject);
        }
      }]
    });
    var app = new vue({
      el: '#app',
      router: router
    });
  </script>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。