大家好,我是你的好朋友思创斯。今天说一说vue路由用法_vue路由挂载,希望您对编程的造诣更进一步.
学习vue-router就要先了解路由是什么?前端路由的实现原理?vue-router如何使用?等等这些问题,就是本篇要探讨的主要问题。
大概有两种说法:从路由的用途上来解释路由就是指随着浏览器地址栏的变化,展示给用户的页面也不相同。从路由的实现原理上来解释路由就是url到函数的映射。
vue router 是 vue.js 官方的路由管理器,它和 vue.js 的核心深度集成。
基于location.hash来实现的。其实现原理也很简单,location.hash的值就是url中#后面的内容。比如下面这个网站,它的location.hash=’#me’:
https://localhost#me
hash也存在下面几个特性:
- url中hash值只是客户端的一种状态,也就是说当向服务器端发出请求时,hash部分不会被发送。
- hash值的改变,都会在浏览器的访问历史中增加一个记录。因此我们能通过浏览器的回退、前进按钮控制hash的切换。
- 我们可以使用hashchange事件来监听hash的变化。
vue-router 默认 hash 模式 —— 使用 url 的 hash 来模拟一个完整的 url,于是当 url 改变时,页面不会重新加载。
如果不想要很丑的 hash,我们可以用路由的 history 模式,只需要在配置路由规则时,加入”mode: ‘history'”,这种模式充分利用 history.pushstate api 来完成 url 跳转而无须重新加载页面。其中做最主要的api有以下两个:history.pushstate()和history.repalcestate()。
const router = new vuerouter({
mode: 'history',
routes: [...]
})
是否还在为ide开发工具频繁失效而烦恼,来吧关注以下公众号获取最新激活方式。亲测可用!
【正版授权,激活自己账号】:
【官方授权 正版激活】:

首先,安装vue-router
npm install vue-router
接下来,在main.js定义 (路由) 组件、安装插件、定义路由、创建 router 实例,然后传 routes 配置、创建和挂载根实例。
import vue from 'vue'
import vuerouter from 'vue-router';
import app from './app.vue'
import './plugins/element.js'
// 1. 定义 (路由) 组件。
import todolist from './components/todolist.vue';
import todolistwithui from './components/todolistwithui.vue'
import todolistwithapi from './components/todolistwithapi.vue'
vue.config.productiontip = false
// 2. 安装插件
vue.use(vuerouter);
// 3. 定义路由
// 每个路由应该映射一个组件。 其中"component" 可以是
// 通过 vue.extend() 创建的组件构造器,或者,只是一个组件配置对象。
const routes = [
{ path: '/noui', component: todolist },
{ path: '/ui', component: todolistwithui },
{ path: '/api', component: todolistwithapi }
]
// 4. 创建 router 实例,然后传 `routes` 配置
// 你还可以传别的配置参数, 不过先这么简单着吧。
const router = new vuerouter({
routes // (缩写) 相当于 routes: routes
})
// 5. 创建和挂载根实例。
// 记得要通过 router 配置参数注入路由,
// 从而让整个应用都有路由功能
new vue({
router,
render: h => h(app),
}).$mount('#app')
最后,app.vue使用 router-link 组件来导航,和放置路由出口 router-view
无ui
有ui
有api
目前为止,我们完成了vue-router的基本用法,是不是还是挺简单的呀。其他动态路由匹配、嵌套路由等用法我们在这里不进行展开了。
文中用到的代码我们放在:https://github.com/zcqiand/miscellaneous/tree/master/vue
文章由思创斯整理,转载请注明出处:https://ispacesoft.com/122814.html