<vue 路由 3、路由代码跳转>
说明:在上一节的工程下继续讲解
一、 知识点说明
业务开发中更多的是使用代码方式进行页面的跳转会用到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页面

五、代码解释
无
资源丰富的的网盘资源:网盘资源大全! 推荐一个适合零基础学习SQL的网站:不用安装数据库,在线轻松学习SQL!
浙公网安备 33010602011771号