<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







Home.vue




About.vue

 


四、效果

1、运行程序

注:要进入到相应的路劲下

 

启动成功后:

 

2、浏览器打开http://localhost:8080/

点击关于按钮就调用方法进行跳转到about页面

 

五、代码解释

vue