Getting started with Vue Router(x4.x)
Vue Router is the official router for Vue.js. It is deeply integrated with the core of Vue.js, making it easy to build single-page applications with Vue.js.
Features include:
- Nested route map
- dynamic routing
- Modular, component-based routing configuration
- Routing parameters, queries, wildcards
- Demonstrates the transition effects provided by the transition system of vue.js
- Detailed navigation controls
- Automatically activate links with CSS classes
- HTML5 history mode or hash mode
- Customizable scrolling behavior
- Correct encoding of URL
Chapter 1 Getting Started
Router routing, because Vue is a single-page application and there will not be so much HTML for us to jump, so we need to use routing as a page jump. Vue routing allows us to access different content through different URLs. Multi-views can be achieved through Vue. Single page web application.
Build front-end project
npm init vue@latest
//或者
npm init vite@latest
Install routing vue-router
// 目前默认版本是4.x版本
yarn add vue-router
或者 npm i vue-router@4
Create a new router folder in the src directory, and then create a new index.js in the router folder.
// 引入路由对象
import {
createRouter, createWebHashHistory } from 'vue-router'
// 1. 定义路由组件.
// 也可以从其他文件导入
import News from '../views/News.vue'
import Fun from '../views/Fun.vue'
// 2. 定义一些路由
// 每个路由都需要映射到一个组件。
// 我们后面再讨论嵌套路由。
const routes = [
{
path: '/news', component: News },
{
path: '/fun', component: Fun },
]
// 3. 创建路由实例并传递 `routes` 配置
// 你可以在这里输入更多的配置,但我们在这里
// 暂时保持简单
const router = createRouter({
// 4. 内部提供了 history 模式的实现。为了简单起见,我们在这里使用 hash 模式。
history: createWebHashHistory(),
routes, // `routes: routes` 的缩写
})
// 导出路由实例 去main.js入口文件 创建并挂载根实例
export default router
router-view
router-view will display the component corresponding to the url. You can place it anywhere to suit your layout.
<template>
<div>
<!-- 路由出口 -->
<!-- 路由匹配到的组件将渲染在这里 -->
<router-view></router-view>
</div>
</template>
Finally mount it in main.js
import {
createApp } from 'vue'
import App from './App.vue'
import router from './router'
createApp(App)
.use(router)
.mount('#app')
Chapter 2 Named Routing and Programmatic Navigation
Named routes . In addition to path, you can also provide a name for any route. This has several advantages:
●No hardcoded URLs
●Prevents you from making typographical errors in URLs.
const routes = [ // 这里可以随意命名 routes1 也可以
{
path: '/news', name: '新闻', component: () => import('../views/News.vue') } // name可以是中文
]
Router-link jump method can change objects
<template>
<div>
<h1>只会番茄炒蛋</h1>
<div>
<!--使用 router-link 组件进行导航 -->
<!--通过传递 `to` 来指定链接 -->
<!--`<router-link>` 将呈现一个带有正确 `href` 属性的 `<a>` 标签-->
<router-link :to="{ name: 'A' }">跳转a</router-link>
<router-link style="margin-left:200px" :to="{ name: 'B' }">跳转b</router-link>
</div>
</div>
</template>
Programmatic navigation (emphasis)
In addition to using the creation of a tag to define navigation links, we can also use the router's instance method to implement it by writing code.
- string pattern
methods: {
gotoNews() {
this.$router.push( '/news' )
}
},
- object mode
methods: {
gotoNews() {
this.$router.push({
path: '/news'
})
}
},
- named routing pattern
methods: {
gotoNews() {
this.$router.push({
name: '新闻'
})
}
},
- a tag jump
can also be jumped directly through a href, but the page will be refreshed.
<a href="/b">a标签跳转</a>
Chapter 3 Routing Parameters (Key Points)
query route parameters
When programmatic navigation uses router push or replace, it is changed to object form and a new query attribute is added.
gotoPlaying() {
this.$router.push({
path: '/playing',
query: {
name: '路由传了个参数 111'
}
})
},
Accept parameters using query in useRoute
<template>
<div>我是playing</div>
<div>{
{
this.$route.query.name }} ········{
{
queryName }}</div>
</template>
<script>
export default {
data() {
return {
queryName: null
};
},
mounted() {
// 在生命周期里
this.queryName = this.$route.query.name // 使用路由传参 方法1 定义data数据
console.log(this.$route.query.name) // 使用路由传参 方法2 直接在{
{}}使用
console.log(this.$route) // 打印看看$route
console.log(this.$router)// 打印看看$router
},
methods: {
},
};
</script>
<style scoped>
</style>
Dynamic routing parameters
Many times, we need to map routes for a given matching pattern to the same component. For example, we might have a User component that should render to all users, but with different user IDs. In Vue Router, we can use a dynamic field in the path to achieve this, we call it the path parameter
Path parameters are represented by colon:. When a route is matched, the value of its params will be exposed in each component as this.$route.params.
export default {
data() {
return {
};
},
mounted() {
console.log(this.$route.params) // 和query一样 可以直接往{
{}}里面插入 可以以赋值给data
},
methods: {
},
};
Chapter 4 Nested Routing
Some application UIs consist of multiple layers of nested components. In this case, the fragment of the URL usually corresponds to a specific nested component structure.
const routes = [ // 这里可以随意命名 routes1 也可以
{
path: '/news', name: '新闻', component: () => import('../views/News.vue') },
{
path: '/playing', component: Playing },
{
path: '/home', name: '玩', component: () => import('../views/Home.vue') },
{
path: '/dynamic/:id', component: () => import('../views/Dynamic.vue') },
{
path: '/user',
component: () => import('../views/User.vue'),
children: [
{
path: '/user/man', component: () => import('../views/Man.vue') },// path的第一种写法把路径带上父级的路径写全
{
path: 'woman', component: () => import('../views/Woman.vue') },// path的第二种写法不带斜杠/ 只写自己的路径
] // 配置完嵌套路由后 别忘了在父级组件里 加上 <router-view></router-view> 路由出口 否则不显示
},
]
As you can see, the children configuration is just another array of routes, just like routes themselves. Therefore, you can continue to nest views according to your needs.
! Don’t forget to add router-view to the nested routing page