一、控制台安装vue路由
npm install --save vue-router@3.5.3 最新版本只支持vue3
二、项目src文件夹下创建router文件夹,并在router文件夹下创建index.js文件
三、在index.js文件夹下进行vue路由配置
//1.导入VueRouter
import Vue from "vue";
import VueRouter from 'vue-router'
// 引入路由组件
import Home from '@/pages/Home'
import Search from '@/pages/Search'
import Login from '@/pages/Login'
import Register from '@/pages/Register'
//2.使用路由
Vue.use(VueRouter);
// 把VueRouter原型对象push,保存一份
let originPush = VueRouter.prototype.push
let originReplace=VueRouter.prototype.replace
// 重写push|replace
// 第一个参数:告诉原来的push方法,往哪里跳转(传递哪些参数)
VueRouter.prototype.push = function (location, resolve, reject) {
if (resolve && reject) {
originPush.call(this, location, resolve, reject)
} else {
originPush.call(this, location, () => { }, () => { })
}
}
VueRouter.prototype.replace=function(location,resolve,reject){
if(resolve&&reject){
originReplace.call(this,location,resolve,reject)
}else{
originReplace.call(this,location,()=>{},()=>{})
}
}
//3.创建VueRouter的实例
const router = new VueRouter({
//tips:不想要 #(锚点)就添加下面代码
mode: 'history',
//4.配置路由的path和组件
routes: [
{
path: "/home",
component: Home,
meta: { show: true }
},
{
path: "/search/:keyword",
component: Search,
meta: { show: true },
name: 'search',
},
{
path: "/login",
component: Login,
meta: { show: false }
},
{
path: "/register",
component: Register,
meta: { show: false }
},
// 重定向,在项目跑起来时,访问/,定向到/home
{
path: '*',
redirect: "/home"
}
]
})
//5.导入路由实例
export default router
四、在main.js中注册路由文章来源:https://www.toymoban.com/news/detail-651975.html
import Vue from 'vue'
import App from './App.vue'
// 引入路由
import router from '@/router/index'
Vue.config.productionTip = false
new Vue({
//注册路由
router,
render: h => h(App),
}).$mount('#app')
五、在App.vue根组件组件使用文章来源地址https://www.toymoban.com/news/detail-651975.html
<router-view></router-view>
到了这里,关于vue2路由配置的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!