vueJs+webpack单页面应用--vue-router配置
vue-route版本要跟vue版本同步,我的vue用的2.0+的,vue-router 也用了最新版2.1+
npm安装vue-router:
$ npm install vue-router --save-dev
使用:
1.引入 vue-router: import VueRouter from 'vue-router';
2.注册: Vue.use(VueRouter);
3.配置路径:
const routes = [
{ path: '/goods', component: goods },
{ path: '/seller', component: seller },
{ path: '/ratings', component: ratings }
];
const router = new VueRouter({
linkActiveClass: 'active',
routes: routes
});
4.初始化Vue(备注:
直接new Vue不赋值 需上面加上 /* eslint-disable no-new */注释
):
/* eslint-disable no-new */
new Vue({
router: router,
...App
}).$mount('#app');
5.push进来第一个路径
router.push('/goods');
main.js源码:
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue'; import App from './App'; import VueRouter from 'vue-router'; import goods from './components/goods/goods'; import seller from './components/seller/seller'; import ratings from './components/ratings/ratings'; Vue.use(VueRouter); const routes = [ { path: '/goods', component: goods }, { path: '/seller', component: seller }, { path: '/ratings', component: ratings } ]; const router = new VueRouter({ linkActiveClass: 'active', routes: routes }); /* eslint-disable no-new */ new Vue({ router: router, ...App }).$mount('#app'); router.push('/goods');
1. 定义路由链接: <router-link to="/goods">商品</router-link>
2. 路由匹配到的组件将渲染在这里 <router-view></router-view>
App.vue 源码:
<template> <div> <v-header></v-header> <div class="tab"> <div class="tab-item"> <router-link to="/goods">商品</router-link> </div> <div class="tab-item"> <router-link to="/ratings">评论</router-link> </div> <div class="tab-item"> <router-link to="/seller">商家</router-link> </div> </div> <!-- 路由匹配到的组件将渲染在这里 --> <router-view></router-view> </div> </template> <script> import header from './components/header/header'; export default { components: { 'v-header': header } }; </script> <style lang="stylus" rel="stylesheet/stylus"> .tab font-size: 28px display: flex .tab-item height: 40px line-height: 40px text-align: center flex: 1 </style>