本文共 3221 字,大约阅读时间需要 10 分钟。
#vue router可以安装为dev依赖npm install vue-router --save-dev
src
----page
--------Page1.vue
--------Page2.vue
----support
--------router
------------index.js
----main.js
----App.vue
import Vue from 'vue';//引入vue router组件import VueRouter from 'vue-router';//引入Page1和Page2两个页面组件import Page1 from '../../pages/Page1.vue'import Page2 from '../../pages/Page2.vue'//路由表,用于配置路由的路径与映射的页面,path为""的即为缺省页面export const routes = [{ path: "", component: Page1, meta: { keepAlive: true }}, { name: 'Page1', path: "/Page1", component: PriceedList, meta: { keepAlive: true }}, { name: 'Page2', path: "/Page2", component: EditPriceed}];//注册组件Vue.use(VueRouter);//使用上面地路由表routes生成VueRouter对象const router = new VueRouter({ routes});//路由的钩子函数,每次路由前都会触发router.beforeEach((to, from, next) => { next();});export default router;
import Vue from 'vue'//引入前面生成的VueRouter对象import router from './support/router'import App from './App.vue'const app = new Vue({ //把router挂载到根实例上,从而可以全局使用 router: router, //将App.vue渲染,并挂载到id为app的元素下,见$mount("#app"), //这并不是必须的,如果路由出口直接位于index.html中,则不需要配置render render: h => h(App)}).$mount("#app");
my title
很多时候我们的App.vue会进行一些定制,为了保持index.html简洁,所以我们使用App.vue来作为应用的路由出口,再将其渲染到index.html中。
如果使用vue-cli创建的项目,你会发现只有App.vue,而没有index.html,这是因为index.html是一个固定的模板,vue已经帮我们维护了。
my title
Go to Page1 Go to Page2
router.push跳转到指定的页面,这个方法回向history栈添加一个记录,点击后退会返回到上一个页面。
this.$router.push({ path: '/Page2'})
这种方式跳转的同时可以携带参数,有query与params两种方式携带参数,query方式是将参数放在url中进行传递,所以刷新后数据依然在,params方式参数不会出现在url中,但刷新后数据即会丢失。
//通过query携带参数//1、跳转this.$router.push({ path: '/Page2', query: { param1: '1', param2: '2' }})//2、在目标页获取参数this.$route.query.param1this.$route.query.param2//通过params携带参数,这种方式路由表中需要配置name//1、跳转this.$router.push({ name: 'Page2', params: { param1: '1', param2: '2' }})//2、目标页获取参数this.$route.param.param1this.$route.param.param2
这个方法的参数是一个整数,意思是在 history 记录中向前或者后退多少步,类似 window.history.go(n)
。
// 在浏览器记录中前进一步,等同于 history.forward()router.go(1)// 后退一步记录,等同于 history.back()router.go(-1)// 前进 3 步记录router.go(3)// 如果 history 记录不够用,那就默默地失败呗router.go(-100)router.go(100)
replace与push类似,也是跳转到指定的页面,但是这个方法不会向history里面添加新的记录,点击返回,会跳转到上上一个页面。上一个记录是不存在的。
vue router有两种模式,hash和history,默认使用的是hash模式。
使用 URL 的 hash 来模拟一个完整的 URL,于是当 URL 改变时,页面不会重新加载。
hash模式有一个缺点是地址栏中的URL不太好看,类似于这种http://localhost/#/Page1
,有一个#符号。
利用HTML5 History Interface 中新增的 history.pushState
和replaceState()
来完成 URL 跳转而无须重新加载页面,需要浏览器支持,history模式的URL也很美观,类似于http://localhost/Page1
,是正常的restful风格。
当路由输入URL错误时,会返回404,所以history模式时,应该做好404异常的处理。
菜鸟教程:https://www.runoob.com/vue2/vue-routing.html
Vue官网教程:https://router.vuejs.org/zh/installation.html
《this.$router.push、replace、go的区别》:https://blog.csdn.net/qq_38614249/article/details/79564563
《vue-router的两种模式的区别》:https://juejin.im/post/5a61908c6fb9a01c9064f20a