1.如果在脚手架中没有勾选中router选项的话,则需要在当前项目中添加router插件:(运行时依赖插件)
npm install vue-router --save
2.在src目录下创建所需文件夹及js文件(src/router/index.js)
3.设置index.js文件
//导入相关模块 import Vue from 'vue' import VueRouter from 'vue-router' //从vue视图中导出相关所需要的视图页面 const Home = () => import('../views/home/Home'); const Profile = () => import('../views/profile/Profile'); //安装插件 Vue.use(VueRouter); //创建路由对象 const routes = [ { //设置默认路径 path: '', redirect: '/home' }, { path: '/home', name: 'home', component: Home }, { path: '/profile', name: 'profile', component: Profile } ] const router = new VueRouter({ routes, //模式不设置时默认为哈希模式 mode: 'history' }); //导出模块 export default router
4.在入口函数main.js中导入及注册router
import Vue from 'vue' import App from './App.vue' import router from './router' Vue.config.productionTip = false new Vue({ router, render: h => h(App) }).$mount('#app')