1、安裝VueRouter
npm install vue-router --save-dev
2、創建路由文件
在項目的`src`目錄下,創建`router.js`文件,用來專門管理路由,接下來所有的路由都寫在這個文件中。
1)導入vue-router
import Vue from "vue"; import VueRouter from "vue-router"; Vue.use(VueRouter);
2) 導入需要路由的組件
在此要注意,需要的導入的組件是要提前創建好的,最好每個組件單獨一個文件。
3)創建路由
再此,只寫個樣例
const routes = [{ path: "/", component: Home, name: "home" }, { path: "/orders", component: Orders, name: "orders" }, { path: "/our", component: Our, name: "our" } ];
4)注冊路由
const router = new VueRouter({ routes });
5)導出路由
// 將路由導出,在main.js中導入 export default router;
3、在main.js中導入路由
import router from "./routes" new Vue({ render: h => h(App), router, }).$mount('#app')
4、在app.vue文件中創建路由出口
// 創建路由出口 <router-view></router-view> // 基於Vant組件添加的路由,在需到跳轉的地方添加"to"指向路由 <van-tabbar v-model="active"> <van-tabbar-item icon="home-o" to="/">首頁</van-tabbar-item> <van-tabbar-item icon="orders-o" to="/orders">訂單</van-tabbar-item> <van-tabbar-item icon="user-o" to="/our">我的</van-tabbar-item> </van-tabbar>