說明:在上一節的工程下繼續講解
一、 知識點說明
業務開發中更多的是使用代碼方式進行頁面的跳轉會用到this.$router.push('/') 和this.$router.replace('/home'),后者就是跳轉后不能返回上一個頁面和前面講的replace對應。
二、代碼結構
注:主要是標紅的幾個文件,這里特別強調一下之前章節的代碼放到“源碼”這個文件夾下

三、代碼
重新編寫這幾個文件中的代碼
index.js
//引入路由
import { createRouter, createWebHistory } from 'vue-router'
import Home from '../views/Home.vue'
//定義路由
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: () => import('../views/About.vue')
}
]
//創建路由
const router = createRouter({
//createWebHashHistory hash模式路徑前面會多一個#號
history: createWebHistory(process.env.BASE_URL),
routes
})
//返回了路由
export default router
App.vue
<template>
<div id="nav">
<!-- <router-link to="/" replace>Home</router-link> |
<router-link to="/about" replace>About</router-link> -->
<button @click="homeClick">首頁</button>
<button @click="aboutClick">關於</button>
</div>
<router-view></router-view>
</template>
<script>
export default {
name: 'App',
methods: {
homeClick() {
// 通過代碼的方式修改路由 vue-router
this.$router.push('/')
//this.$router.replace('/home')
console.log('homeClick');
},
aboutClick() {
this.$router.push('/about')
//this.$router.replace('/about')
console.log('aboutClick');
}
}
}
</script>
<style>
</style>
Home.vue
<template>
<div class="home">
<p>Home Page</p>
<img alt="Vue logo" src="../assets/logo.png">
</div>
</template>
<script>
</script>
About.vue
<template>
<div class="about">
<h1>This is an about page</h1>
</div>
</template>
四、效果
1、運行程序
注:要進入到相應的路勁下

啟動成功后:

2、瀏覽器打開http://localhost:8080/
點擊關於按鈕就調用方法進行跳轉到about頁面

五、代碼解釋
無
