Vue-Router 4.x


routing configuration

Differences from the previous version:

  1. createRouter()replaced bynew Router()
  2. Route patterns are createWebHistory()replacedmode: 'history'
  3. in main.js .use(router)replacednew Vue({ router })

The previous version of writing:

// router/index.js
import Vue from 'vue';
import Router from 'vue-router';
import routes from './routes'

Vue.use(Router);

const router = new Router({
    
      // 区别1
	mode: 'history',  // 区别2
	routes
});

export default router;


// main.js
import Vue from 'vue'
import router from './router'
// ...
new Vue({
    
    
	el: '#app',
	router,   // 区别3
	components: {
    
     App },
	template: '<App/>'
})

vue-router 4.xVersion writing:

// router/index.js
import {
    
     createRouter, createWebHistory } from 'vue-router';
import routes from './routes'

const router = createRouter({
    
     // 区别1
	history: createWebHistory(process.env.BASE_URL),  // 区别2
	routes 
})

export default router 


// main.js
import {
    
     createApp } from 'vue'
import App from './App.vue'
import router from './router'

const app = createApp(App);
createApp(App).use(router).mount('#app');  // 区别3

Routing mode difference:

vue-router 3.x vue-router 4.x
history createWebHistory()
hash createWebHashHistory()
abstract createMemoryHistory()

Routing jump and parameters

router: It is a global object of VueRouter , an instance object obtained through the constructor function, which contains all routes and contains many key objects and Vue.use(VueRouter)propertiesVueRouter

route: is a local object of a jump route , each route will have a route object, you can get the corresponding name, path, params, queryetc.

The above is consistent vue2.xwith the above, we should pay attention to the distinction. .vue3.x

In vue3.x setup中, useRouter, useRouteusually used to:

  • useRouter: Routing jump
  • useRoute: Get routing parameters
<script setup>
	import {
      
       useRoute, useRouter } from 'vue-router'
	const router = useRouter();
	const route = useRoute();

	console.log(route); // 获取路由参数
	router.push('/logo'); // 进行路由跳转
</script>

Get routing parameters in vue-router 3.x :

  1. In a component: { {$route.query.color}}or{ {$route.params.color}}

  2. In JS: this.$route.query.colororthis.$route.params.color


Routing (navigation) guards

Simply put, the routing guard is the function of monitoring page entry , modification , and departure .

Each guard accepts three parameters:

  • to: the routing object that is about to enter
  • from: the route that the current navigation is leaving
  • next: This method must be called to resolve this hook. The execution effect depends on the calling parameters of the next method.

About next:

  1. next(): Proceed to the next hook in the pipeline. If all hooks are executed, the state of the navigation is confirmed (confirmed).
  2. next(false): Interrupt the current navigation. If the URL of the browser changes (perhaps manually by the user or the browser's back button), the URL address will be reset to the address corresponding to the from route.
  3. next('/')Or next({ path: '/' }): Jump to a different address. The current navigation is interrupted and a new one is started.
  4. next(error):(2.4.0+) If the parameter passed to next is an Error instance, the navigation will be terminated and the error will be passed to the callback registered with router.onError().

In vue-router 3.x:

<script type="text/ecmascript-6">
	export default {
      
      
	
			beforeRouteEnter(to, from, next){
      
      
			    // 在渲染该组件的对应路由被confirm前调用
			    // 此时组件实例还没被创建,因此不能获取`this`
			}
			
			beforeRouteUpdate(to, from, next){
      
      
			    // 在当前路由改变,但该组件被复用时调用
			    // 举例:对于一个带有动态参数的路径`/item/:id`,在`/item/1`和`/item/2`之间跳转的时候,
			    // 由于会渲染相同的`Item`组件,因此组件实例会被复用,从而触发这个钩子
			    // 此时可以获取到`this`
			}
			
			beforeRouteLeave(to, from, next){
      
      
			    // 导航离开该组件的对应路由时调用
			    // 时可以获取到`this`
			}
			
	    }
	};
</script>

In vue-router 4.x:

vue-router 3.x vue-router 4.x
beforeRouteEnter none
beforeRouteUpdate onBeforeRouteUpdate
beforeRouteLeave onBeforeRouteLeave

In setup, since the routing has already happened, it doesn't make sense setupto set it internally , so there is nobeforeRouteEnteronBeforeRouteEnter

<script>
import {
      
       onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router';
export default {
      
      
    setup() {
      
      
        onBeforeRouteLeave((to, from) => {
      
      
            alert('你真的想离开吗?您有未保存的更改!');
        });

        onBeforeRouteUpdate(async (to, from) => {
      
      
            if (to.params.id !== from.params.id) {
      
      
                // ...
            }
        });
    }
};
</script>

dynamic routing

Dynamic routing parameter id:

<!-- 导航页 -->
<template>
    <router-link :to="'/news/' + newsId">新闻详情</router-link>
</template>

<script setup>
import {
      
       ref } from 'vue';
const newsId = ref('001');
</script>

Get route parameters:

<!-- 新闻详情页 -->
<template>
  <div id="news">
      <p>id:{
   
   {$route.params.id}}</p>
      <p>{
   
   {newsId}}</p>
  </div>
</template>


<script setup>
import {
      
      useRoute} from 'vue-router';
import {
      
      computed} from 'vue';
const route=useRoute();

const newsId=computed(()=>{
      
      
   return route.params.id
})
</script>

Routing lazy loading

//router/index.js
import Home from '../component/Home.vue'
import Mine from '../component/Mine.vue'
import News from '../component/News.vue'

const routes = [
  {
    
     path: "/", redirect: "/home" },
  {
    
     path: "/home", component: Home },
  {
    
     path: "/mine", component: Mine },
  {
    
     path: "/news/:id", component: News },
];

Change to lazy loading:

const routes = [
  {
    
     path: "/", redirect: "/home" },
  {
    
     path: "/home", component: () => import("@/views/Home.vue") },
  {
    
     path: "/mine", component: () => import("@/views/Mine.vue") },
  {
    
     path: "/news/:id", component: () => import("@/views/News.vue") }
]

keep-alive

You can use the orkeep-alive attribute (include and exclude include the name of the component is not the router name) to set the cache:includeexclude

  • includeThe component name whose value is a string or a regular expression match will be cached .
  • excludeComponent name whose value matches a string or a regular expression will not be cached .

Vue2.x writing method:

<keep-alive exclude="Home">  // 缓存除了Home外的所有组件
   <router-view></router-view>
</keep-alive>

Vue3.x writing method:

<template>
	<router-view v-slot="{ Component }">
	    <keep-alive :include="includeList">
	        <component :is="Component" />
	    </keep-alive>
	</router-view>
</template>

<script setup>
import {
      
       ref } from 'vue';

// 需要缓存的组件name值
const includeList = ref(['About', 'User']); // 缓存About和User组件
</script>

You can also router.jsadd metaattribute dynamic judgment in:

meta: {
    
     title: '缓存页面', keepAlive: true }
import {
    
     watch } from 'vue'
import {
    
    useRouter} from 'vue-router'

const router =useRouter()
const includeList = [];

watch(() => router.currentRoute.value,(val) => {
    
    
  // 只要设置了keepAlive属性的,全部加入缓存列表中
  if (val.meta.keepAlive && keepAliveList.indexOf(val.name) === -1) {
    
    
    includeList.push(val.name);
  }
},{
    
    immediate: true,deep: true})

Guess you like

Origin blog.csdn.net/x550392236/article/details/124683620