1.npm安装vuex
npm install vue-router --save-dev
2.文件
在项目根目录 router/index.js
3.配置路由 文件store/index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)
const routes = [
{
path: '/login',
name: 'login',
component: () => import( '../views/login/index')
},
{
path: '/home',
name: 'home',
redirect: '/index', //重定向
meta:{
title:'首页'
},
component: () => import( '../layout/index'),
children:[ //子路由
{
path: '/index', //首页
name: 'index',
component: () => import( '../views/home/index')
}
]
}
]
const router = new VueRouter({
routes
})
export default router
4.将router挂载到当前项目的Vue实例当中去
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router, //挂载到这个vue实例中
render: h => h(App)
}).$mount('#app')
页面中跳转路由
<router-link to="/home">Home</router-link>
跳转后显示路由
<router-view></router-view>
js中使用
fn1() {
// 通过路由名称跳转,配置params参数。
this.$router.replace({ name: 'index', params: { id: Math.random() } });
},
fn2() {
// 直接跳转路由地址,参数直接带在路径中。
this.$router.push(`/home/${Math.random()}`);
},
fn3() {
// 通过路由地址进行跳转,配置query参数。
this.$router.push({ path: '/home', query: { userId: 321 } });
},
fn4() {
console.log(this.$router)
this.$router.go(1)
},
fn5() {
this.$router.forward()
},
fn6() {
this.$router.go(-1)
},
fn7() {
this.$router.back()
}
路由监听
watch: {
// 监听路由跳转。
$route(newRoute, oldRoute) {
console.log('watch', newRoute, oldRoute)
},
},