Vue2 和 Vue3 在路由使用上有以下一些差别:
一、安装和引入方式
1. Vue2:
- 安装路由: npm install vue-router@3 。
- 引入路由:通常在入口文件中引入 VueRouter 和创建路由实例,并使用 Vue.use(VueRouter) 安装路由插件。
import Vue from 'vue';
import VueRouter from 'vue-router';
Vue.use(VueRouter);
2. Vue3:
- 安装路由: npm install vue-router@4 。
- 引入路由:无需使用 Vue.use() 安装插件,直接在入口文件中引入并使用路由。
import { createApp } from 'vue';
import { createRouter, createWebHistory } from 'vue-router';
二、路由配置方式
1. Vue2:
- 路由配置对象通常包含 path 、 component 、 name 等属性,组件是直接通过字符串引入。
const routes = [
{
path: '/home',
component: 'Home',
name: 'home'
}
];
2. Vue3:
- 路由配置对象中组件使用函数形式动态引入,提高性能。
const routes = [
{
path: '/home',
component: () => import('./views/Home.vue'),
name: 'home'
}
];
三、路由模式设置
1. Vue2:
- 使用 new VueRouter({ mode: 'history' }) 设置路由模式为 history 模式。
const router = new VueRouter({
mode: 'history',
routes
});
2. Vue3:
- 通过 createWebHistory() (对应 history 模式)或 createWebHashHistory() (对应 hash 模式)函数来设置路由模式,并传递给 createRouter 。
const router = createRouter({
history: createWebHistory(),
routes
});
四、使用方式
1. Vue2:
- 在组件中通过 this.$router 和 this.$route 访问路由实例和当前路由信息。
<template>
<div>
<p>Current route path: {{ $route.path }}</p>
<button @click="$router.push('/another-page')">Go to Another Page</button>
</div>
</template>
2. Vue3:
- 通过 useRouter 和 useRoute 函数来访问路由实例和当前路由信息。
<template>
<div>
<p>Current route path: {{ $route.path }}</p>
<button @click="goToAnotherPage">Go to Another Page</button>
</div>
</template>
<script>
import { useRouter, useRoute } from 'vue-router';
export default {
setup() {
const router = useRouter();
const route = useRoute();
const goToAnotherPage = () => router.push('/another-page');
return {
$route: route,
goToAnotherPage
};
}
};
</script>