一、什么是路由?vue-router中文官网:https://router.vuejs.org/zh/
vue router 是 vue.js 官方的路由管理器。它和 vue.js 的核心深度集成,让构建单页面应用变得易如反掌。路由实际上就是可以理解为指向,就是我在页面上点击一个按钮需要跳转到对应的页面,这就是路由跳转;
首先我们来学习三个单词(route,routes,router):
route:首先它是个单数,译为路由,即我们可以理解为单个路由或者某一个路由;
routes:它是个复数,表示多个的集合才能为复数;即我们可以理解为多个路由的集合,js中表示多种不同状态的集合的形式只有数组和对象两种,事实上官方定义routes是一个数组;所以我们记住了,routes表示多个数组的集合;
router:译为路由器,上面都是路由,这个是路由器,我们可以理解为一个容器包含上述两个或者说它是一个管理者,负责管理上述两个;举个常见的场景的例子:当用户在页面上点击按钮的时候,这个时候router就会去routes中去查找route,就是说路由器会去路由集合中找对应的路由;【相关推荐:vue.js视频教程】
二、使用步骤1.创建项目
安装好项目后,项目目录如下:
2.安装路由
打开项目下 package.json文件,查看 vue 版本。
vue 版本为 2.x,建议 vue-router 安装 3.x 版本。
vue 版本为 3.x,建议 vue-router 安装 4.x 版本。
随后在该项目目录下输入命令
npm install vue-router@版本号
3.创建文件
打开 src 文件夹,创建以下几个文件(有的默认创建好了)
1.helloworld.vue文件该文件为默认创建文件,为了演示方便删除多余代码
<template> <div class="hello"> <h1>helloworld</h1> </div></template><script>export default { name: 'helloworld', props: { msg: string }}</script><!-- add "scoped" attribute to limit css to this component only --><style scoped>h3 { margin: 40px 0 0;}ul { list-style-type: none; padding: 0;}li { display: inline-block; margin: 0 10px;}a { color: #42b983;}</style>
2.test.vue文件<template> <div> <h2>test</h2> </div></template><script> // 导出 export default { name: 'testitem' }</script><style></style>
3.index.js文件// 引入vueimport vue from 'vue';// 引入vue-routerimport vuerouter from 'vue-router';// 注册 第三方库需要use一下才能用vue.use(vuerouter)// 引入helloworld页面import helloworld from '../components/helloworld.vue'// 引入test页面import test from '../components/test.vue'// 定义routes路由的集合,数组类型const routes=[ //单个路由均为对象类型,path代表的是路径,component代表组件 {path:'/hw',component:helloworld}, {path:"/test",component:test}]// 实例化vuerouter并将routes添加进去const router = new vuerouter({// es6简写,等于routes:routes routes});// 抛出这个这个实例对象方便外部读取以及访问export default router
4.main.js文件import vue from 'vue'import app from './app.vue'import router from './router/index.js'// 阻止vue在启动时生成的生产提示vue.config.productiontip = falsenew vue({ router: router, render: h => h(app),}).$mount('#app')
5.app.vue文件<template> <div id="app"> <!--使用 router-link 组件进行导航 --> <!--通过传递 `to` 来指定链接 --> <!--`<router-link>` 将呈现一个带有正确 `href` 属性的 `<a>` 标签--> <router-link to="/hw">helloworld</router-link> <router-link to="/test">test</router-link> <hr> <!-- 路由出口 --> <!-- 路由匹配到的组件将渲染在这里 --> <router-view></router-view> </div></template><script>export default { name: 'app',}</script><style>#app { font-family: avenir, helvetica, arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px;}</style>
三.运行项目1.在项目文件下打开cmd,输入yarn serve
2.打开浏览器,访问 http://localhost:8080/
3.点击helloworld,页面无需刷新,跳转至http://localhost:8080/#/hw
4.点击test,页面无需刷新,跳转至http://localhost:8080/#/test
以上就是vue router路由流程简单梳理(使用步骤)的详细内容。
