Day18-Vue Router 路由设定(part1)

昨天有提到的路由今天要来做拆解,做更深入的了解。昨天提到的router/index.js设定也可以写成像书中的方式,里面有两个今天要研究的重点historyroutes

import { createRouter, createWebHistory } from 'vue-router' 
import Home from './views/Home.vue' 
import About from './views/About.vue' 

export const router = createRouter({ 
	history: createWebHistory(), 
	routes: [ 
		{ path: '/', component: Home }, 
		{ path: '/about', component: About }, 
	], 
});

history路由模式

安装的时候有问说要不要采用history mode就是指这里!! 他有两种不同的方式,分别为Hash ModeHTML5 (History API) Mode

Hash模式

顾名思义就是利用#做页面的切换,history设定成createWebHashHistory就可以开始Hash模式,预设路径为location.pathname/根目录,想另外加路径的话可以createWebHashHistory('/folder/')处理,得出的就会是https://example.com/folder/#

缺点: 搜寻引擎会忽略#,不利於SEO

export const router = createRouter({ 
	history: createWebHashHistory(), 
	routes: [ 
		..., 
	], 
});

HTML5 (History API) Mode模式

使用此模式实现转跳页面不需要重新载入页面,此外没有#的url,如https://example.com/folder,但这模式必须搭配後端路由,不然当使用者用http://oursite.com/folder就会出现404错误页面了。(btw加路径的方式和Hash模式一样)

export const router = createRouter({ 
	history: createWebHistory(), 
	routes: [ 
		..., 
	], 
});

routes路由比对

用一开始制作的范例来说明(颜色框代表同一区),http://localhost:8081/下会放入Home元件,也就是说path:'/About'时会使用About元件。

Untitled

动态路由

使不同的path指向同一个component。资料夹内容如下
动态路由
step1 : main.js进入点

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

const app = createApp(App).use(router)
app.mount('#app')

step2 : App.vue中用v-for的方式做出五个link

<template>
  <ul>
    <li v-for="i in 5" :key="i">
      <router-link :to="`/users/${i}`"> /users/{{ i }} </router-link>
    </li>
  </ul>
  <router-view></router-view>
</template>

step3 : router.js设定路径。使用:符号就可以将userId传入User元件,User元件也可以利用this.$route.params.userId取得参数($route这部分官方文件有其他用法与说明)

import { createRouter, createWebHistory } from "vue-router";
import User from "./views/User.vue";

export const router = createRouter({
    history: createWebHistory(),
    routes: [{ path: "/users/:userId", component: User }]
});

step4 : User.vue元件将取地的参数做处理,透过watch监测userId的更新还重新渲染相对应的资料

<template>
  <h1>UserID: {{ $route.params.userId }}</h1>

  <pre>{{ userInfo }}</pre>
</template>

<script>
export default {
  data() {
    return {
      userInfo: {},
    };
  },
  computed: {
    userId() {
      return this.$route.params.userId;
    },
  },
  watch: {
    userId: async function (val) {
      this.userInfo = await this.fetchUserInfo(val);
    },
  },
  methods: {
    async fetchUserInfo(id) {
      return await fetch("https://jsonplaceholder.typicode.com/users/" + id)
        .then((response) => response.json())
        .then((json) => json);
    },
  },
  async created() {
    this.userInfo = await this.fetchUserInfo(this.userId);
  },
};
</script>

自订路由参数

可以利用正规表达式(Regexp)自定义传递

const routes = [ 
	// /:orderId -> 只能是数字 
	{ path: '/:orderId(\\d+)' }, 
	// /:productName -> 无限制 
	{ path: '/:productName' },
]

路由对比失败(找不到网页)

如果读取到不存在的URL可以用/:pathMatch(.*)*来让所有路由连到此元件

const routes = [
  // will match everything and put it under `$route.params.pathMatch`
  { path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound },

  // will match anything starting with `/user-` and put it under `$route.params.afterUser`
  { path: '/user-:afterUser(.*)', component: UserGeneric },
]

非强制的路由参数

?可以让使/users/users/xxx都会被带到指定的元件。

const routes = [ 
	// will match /users and /users/posva 
	{ path: '/users/:userId?' }, 
	// will match /users and /users/42 
	{ path: '/users/:userId(\\d+)?' }, 
]

<<:  RDS Transacrion

>>:  【从零开始的Swift开发心路历程-Day21】简单介绍UIPickerView

【Day15】数据展示元件 - Carousel

元件介绍 Carousel 是一个像旋转木马一样会轮流转的轮播元件。在一个内容空间有限的可视范围中进...

Day13:今天来聊一下Microsoft Defender for Endpoint的配置警报和检测

Microsoft Defender for Endpoint 提供警报和检测的配置选项。 配置包括...

day20 在ui蒐集flow,能取代liveData吗?

好的,前一篇讲到了flow可以完全取代liveData,其实错!! 直接从结论开始讲,flow并不支...

「认知」是你观望世界的窗,不时擦拭,光线才能穿透。

「认知」是你观望世界的窗,不时擦拭,光线才能穿透。 Your assumptions are you...

【Day 1】前言、时程规划

嗨大家! 在大二升大三的这个暑假,系上很多同学申请了实习、规划了 project 实作,却因为疫情升...