天天看點

Vue3配置路由

學路由的時候建的是Vue2項目,剛做了個小項目是Vue3的,和2有點差别,費了一番功夫才搞好,官網上似乎沒更新Vue3的寫法,網上也沒找到比較詳細說這個的,就來貼一下。

在配路由這裡,Vue2和Vue3的差别就在于Vue3不再使用new Vue這種方式建立執行個體,而是使用createApp.

貌似在建立路由對象的時候一定要寫什麼模式,不然沒用,就是在這個地方卡了很久。一開始沒有設定什麼模式,router裡隻有一個參數route,然後就啥也顯示不出來,後來加入了模式就OK了,不知道啥原因,也不報錯,網上也說可以不加這個參數。

//router/index.js

import { createRouter, createWebHistory } from 'vue-router'

const routes = [
  {
    path: '/DefaultPage',
    name: 'DefaultPage',
    component: () => import('../views/DefaultPage.vue'),
    children: []
  },
  {
    path: '/PrincipalSheet',
    name: 'PrincipalSheet',
    component: () => import('../views/PrincipalSheet.vue')
  }
]

const router = createRouter({

  history: createWebHistory(),
  routes // 使用上方定義的路由配置
})
// //防止多次點選報錯
// const originalPush = VueRouter.prototype.push
//    VueRouter.prototype.push = function push(location) {
//    return originalPush.call(this, location).catch(err => err);
// }
export default router
           
//main.js
import { createApp } from 'vue'
import App from './App.vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
import router from './router'
axios.defaults.baseURL = 'http://localhost:8082/mylofter/'

const app = createApp(App)
app.use(router)
app.use(VueAxios, axios).mount('#app')
           

繼續閱讀