说明:在上一节的工程下继续讲解

一、     知识点说明

  业务开发中更多的是使用代码方式进行页面的跳转会用到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页面

 

 

 

五、代码解释


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM