Vue2和Vue3路由使用差别

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>

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值