首先npm安裝vue-router插件,就不說了
其次:
先看下我本地的目錄結構吧
第一步:在src目錄下新建一個專門存放router的index.js文件
里面的內容為:
import Vue from 'vue' //注:這句必須要有,雖然在main.js里面已經引入過Vue,但是這里不要這句的話,就直接報錯了Vue is not defined import VueRouter from 'vue-router' import conOne from '@/views/conOne' Vue.use(VueRouter) export default new VueRouter({ mode:'history', routes:[ //注:此處的方法名,記住這里是routes,不是routers,沒有r,要是寫成routers,控制台不會報錯,就是渲染不出組件來,牢記啊!不然會讓人崩潰的 { path:'/conone', name:'conOne', component:conOne //注:此處容易跟着代碼提示一不小心寫成components,要注意,控制台報錯TypeError: Cannot read property '$createElement' of undefined
} ] });
第二步:然后在main.js里面的內容
import Vue from 'vue' import App from './App' import router from './router' //import后面的router只能寫成router,且首字母大寫都不行,不然在下面new Vue里面注入的時候控制台會報錯Cannot read property 'matched'
of undefined,為什么會這樣,目前我也不太清楚,還望大佬指點 Vue.config.productionTip = false new Vue({ el: '#app', router, //記得在這里注入引入的router components: { App }, template: '<App/>' })
第三步:
在項目入口文件app.vue里面加上<router-view></router-view> //不加的話控制台不報錯,但是組件始終渲染不出來,以前不熟悉的時候忘了在這里寫上視圖容器反正糾結過很久
<template> <div id="app"> <router-view></router-view> </div> </template> <script> export default { name: 'App', data(){ return{ } }, } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
容易出錯的地方大概有以下幾點
1.新建的router文件夾的index.js文件沒有引入import Vue from 'vue'這句話,導致報錯Vue is not defined
2.在new VueRouter實例中的數組變量名routes寫成routers,控制台不報錯,但就是渲染不出組件內容,這也是最容易忽略也最容易犯錯,也是最難排查到問題原因的地方(個人認為)
3.main.js中引入router配置文件時命名變量名不是router,或者首字母寫成大寫,導致報錯Cannot read property 'matched'
4.接着第三點在引入了router之后,容易忘記在下面new Vue實例中注入,報錯Cannot read property 'matched' of undefined"
5.在app.vue里面忘了寫路由視圖組件<router-view></router-view>,一般來說,頭腦清晰,又稍微熟悉一點路由是不會犯這個錯的