1 Vue2配合Vue-router3
说多了没用,直接上代码
import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter) const routes = [{ path: '/', name: '首页', component: () => import( /* webpackChunkName: "page" */ '@/views/index'), meta: { requireAuth: true, }, children: [{ path: '/index', name: '首页', component: () => import( /* webpackChunkName: "page" */ '@/views/wel'), meta: { requireAuth: true, } }] }] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router
复制
上面这种写法是比较通用的,配置的是动态路由,前台只配置常用的几个即可。
2 Vue3配合Vue-router4
import { createRouter, createWebHistory } from "vue-router"; import login from "../views/login.vue"; import index from "../views/index.vue"; const routes = [ { path: "/login", name: "登录", component: login, meta: { requireAuth: false, }, }, { path: "/", name: "首页", component: index, meta: { requireAuth: true, }, }, ]; const router = createRouter({ history: createWebHistory(process.env.BASE_URL), routes }); export default router;
复制
导入createRouter, createWebHistory这两个方法,使用createWebHistory方法创建一个routerHistory对象,使用 createRouter 创建路由器。
3 跳转
Vue3和Vue2版本跳转区别挺大,因为this的问题。
Vue2跳转
this.$router.push({ path: "/index" });
复制
Vue3跳转
import { useRoute, useRouter } from "vue-router"; export default { setup(props, context) { // 获取路由器实例 const router = useRouter(); // route是响应式对象,可监控器变化 const route = useRoute(); const onSubmit = e => { e.preventDefault(); validate() .then(() => { login(state.login).then(res => { if (res.code == 0) { router.push("/"); } }); }) .catch(err => {}); }; } };
复制
可以看到,Vue3,需要单独引入。