(五)安装vue-router路由模块,以及实现 <router-link>页面跳转的原理分析
路由跳转的原理其实就是将组件挂载到对应的路径下面,引用组件的时候就对应了页面的具体路径,而挂载的路径只是客户访问得时候的路径,
当访问到呢个挂载组件的路径时,会找到对应的组件,从而跳转到该组件对应的具体页面的路径
1:安装 vue-router
yarn add vue-router (旧版本得)
yarn add vue-router@4 (新版本得)
2:卸载 vue-router
yarn remove vue-router (旧版本得)
npm uninstall vue-router@4 (新版本得)
3:先任意创建3个页面(home.vue,news.vue,user.vue),在创建router.js,将组件挂载到对应的路径下面
import {createRouter,createWebHashHistory} from 'vue-router' //引用组件 import Home from './components/home.vue'//引用组件 import News from './components/news.vue' import Users from './components/user.vue' //使用组件里面的createRouter,createWebHashHistory两个模块实现创建路由,和创建模式选择 const router = createRouter({//创建路由 // 内部提供了 history 模式的实现。为了简单起见,我们在这里使用 hash 模式。 history: createWebHashHistory(), routes:[ //挂载组件,将组件Home挂载到对应的/NewsPath路径下面去,http://192.168.1.2:8084/#/NewsPath就能访问news.vue { path: '/', component: Home }, { path: '/NewsPath', component: News }, { path: '/UserPath', component: Users }, ] }) //将router暴露出去,让引用他的地方可以用router export default router 4:在main.js中挂载路由 import { createApp } from 'vue' import App from './App.vue' import router from './router'; const app=createApp(App); //挂载路由 app.use(router) app.mount('#app1') 5:在App.vue通过 router-view>渲染组件,并且通过
-
tohome -
tonewspath -
touserpath
项目目录文件截图
运行效果(点击3个按钮实现home,news,user这3个页面对应的跳转):