vue-router 例子程序搭建

想看一下vue-router 源代码,所以要先搭建一个环境。

1) 下载Vue.js 源代码

       https://cn.vuejs.org/v2/guide/installation.html  中选择开发版本,就可以把vue.js下载下来了

2) 下载vue-router源代码

      https://router.vuejs.org/zh/installation.html 中选择https://unpkg.com/vue-router/dist/vue-router.js 打开后,另存为就可以了。

3) 写个例子程序如下:

     

<html>
 
<head>
<style type="text/css">

</style>
</head>
 
<body>
 
<script src="./vue.js"></script>
<script src="./vue-router.js"></script>


<div id="app">
    <router-link to='/foo'>go to foo</router-link>
    <router-link to='/bar'>go to bar</router-link>

    <router-view></router-view>
</div>

<script>

const Foo = {template : '<div>foo</div>'}
const Bar = {template : '<div>bar</div>'}

const routes = [
    {path: '/foo', component: Foo},
    {path: '/bar', component: Bar}
];

const router = new VueRouter({
    routes
});

const app = new Vue({
    router
}).$mount("#app");
</script>
 
</body>
</html>

刚开始自己写的时候老是出不来 foo 和 bar。经定位发现是定义routes有问题。出错代码如下:

const routers = [
    {path: '/foo', component: Foo},
    {path: '/bar', component: Bar}
];

const router = new VueRouter({
    routers
});

看出来没有,把routes 写成了routers了。 在new VueRouter示例的时候传递的对象参数中的字段必须是routes,不能是routers。

这个不是随便写的。

因为在源码中有对此的处理:

  var VueRouter = function VueRouter (options) {
    if ( options === void 0 ) options = {};
    console.log("new VueRouter")
    this.app = null;
    this.apps = [];
    this.options = options;
    this.beforeHooks = [];
    this.resolveHooks = [];
    this.afterHooks = [];
    this.matcher = createMatcher(options.routes || [], this);

    var mode = options.mode || 'hash';
    this.fallback = mode === 'history' && !supportsPushState && options.fallback !== false;
    if (this.fallback) {
      mode = 'hash';
    }
    if (!inBrowser) {
      mode = 'abstract';
    }
    this.mode = mode;

    switch (mode) {
      case 'history':
        this.history = new HTML5History(this, options.base);
        break
      case 'hash':
        this.history = new HashHistory(this, options.base, this.fallback);
        break
      case 'abstract':
        this.history = new AbstractHistory(this, options.base);
        break
      default:
        {
          assert(false, ("invalid mode: " + mode));
        }
    }
  };

看到这一行了没:    this.matcher = createMatcher(options.routes || [], this);

这一行就要求是routes而不能是routers。

 

 


版权声明:本文为liubangbo原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。