使用路由vue-router2

首先安装 vue-router:

npm install vue-router --save

修改main.js:

1.引入APP,about两个组件导入router组件
引入子组件Child

    import App from './src/index.vue';
    import About from './src/about.vue';
    import Child from './src/children.vue' 
    import VueRouter from 'vue-router';

    Vue.use(VueRouter)

2.定义路由:
嵌套路由用children:[]存放,子组件在父组件的

<router-view></router-view>

中渲染,路由通过 "/:id" 定义参数通过链接 "/about/123"传递参数
在组件中通过{{$route.params.id}}获取传参

const routes = [
    { path: '/index', component: App },
    { path: '/about/:id', component: About ,children:[
        { path: 'child', component: child}
    ]}
]
  1. 创建 router 实例,然后传 routes 配置
    const router = new VueRouter({
        routes // (缩写)相当于 routes: routes
    })
  1. 创建和挂载根实例。
    const app = new Vue({
        router
    }).$mount('#main')

5.修改index.html文件

    <div id="main">
        <p>
            <router-link to="/index">index</router-link>
            <router-link to="/about/123">about</router-link>
            <router-link to="/about/123/child">child router</router-link>
        </p>
        <!-- 路由匹配到的组件将渲染在这里 -->
        <router-view></router-view>
    </div>

6.修改父组件about.vue
写</template>才发现,只能有一个顶级的HTML标签

</template>
    <div>
        <div class="message">{{ msg }}</div>
        <div>
        <span>传递的参数为:{{ $route.params.id }}</span>

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

8.1路由重定向redirect

routes: [
    ...
    { path: '/a', redirect: '/index' }
  ]

访问/a时将跳转值/index对应的组件

8.2 路由懒加载

用vue.js写单页面应用时,会出现打包后的JavaScript包非常大,影响页面加载,我们可以利用路由的懒加载去优化这个问题。将路由写法改为:

//定义路由
const routes = [
    { path: '/index', component: resolve => require(['./src/index.vue'], resolve) },
    {
        path: '/about/:id', component: resolve => require(['./src/about.vue'], resolve) ,
        children:[
            { path: 'child', component: resolve => require(['./src/children.vue'], resolve)}
    ]},
    { path: '/a', redirect: '/index' }
]

8.3 js的方法跳转路由

    // 字符串
    router.push('home')
    // 对象
    router.push({ path: 'home' })
    // 命名的路由
    router.push({ name: 'user', params: { userId: 123 }})
    // 带查询参数,变成 /register?plan=private
    router.push({ path: 'register', query: { plan: 'private' }})
————————————————