vue学习笔记 十四、页面跳转
系列导航 | ||
---|---|---|
一、 效果:
二、项目结构截图
三、代码
index.js
import { createRouter, createWebHistory,createWebHashHistory } from 'vue-router' import Home from '../views/Home.vue' //路由的配置属组 //paht:路由路劲 必须以/开头 必填 //component:对应的路由组件 必填 //name:路由的名字 const routes = [ { path: '/', name: 'Home', component: Home }, { path: '/about', name: 'About', //按需引入 //如果没有访问/about 就不会加载这个组件 节约性能 component: () => import( '../views/About.vue') } ] //创建路由对象 const router = createRouter({ //createWebHashHistory hash模式路径前面会多一个#号 history: createWebHistory(process.env.BASE_URL), routes }) export default router
About.vue
<template> <div class="about"> <h1>这是about page</h1> <button @click="back">回到首页</button> </div> </template> <script> import {defineComponent} from 'vue' import {useRouter} from 'vue-router' export default defineComponent({ name :'About', setup(){ let router = useRouter() let back = ()=>{ //都是返回上一步 router.back() //router.go(-1) } return { back } } }) </script>
Home.vue
<template> <div> <button @click="goto">跳转路由</button> </div> </template> <script> import {defineComponent,computed,ref } from 'vue' import {useStore} from 'vuex' import {useRouter,useRoute} from 'vue-router' export default defineComponent({ name:'Home', components:{ }, setup(){ //router 是全局路由对象 let router = useRouter() console.log(router) let goto = ()=> { //跳转路由 //push函数里面可以直接传入跳转的路径 //back:上一页 //forward:下一页 //go(整数) 整数代表前进 负数代表后退 //router.push('/about') router.push({path : '/about'}) } return{ goto } } }) </script> <style scoped lang="scss"> </style>