Vue开发之基础路由 (3)

修改src/router/router.js文件,为名为"home"的路由设置别名

import Home from '@/views/Home.vue' export default [ { path: 'http://www.likecs.com/', name: 'home', alias:'/home_page', component: Home, }, { path: '/about', name: 'about', component: () => import('@/views/About.vue'), },{ path:'/argu/:name', component:() => import('@/views/argu.vue') },{ path:'/parent', component:() => import('@/views/parent.vue'), children:[ { path:'child', component:() => import('@/views/child.vue') } ] },{ path:'/named_view', components:{ default: () => import('@/views/child.vue'), view1: () => import('@/views/view1.vue'), view2: () => import('@/views/view2.vue'), } }, { path: '/about_path', redirect: to => '/named_view' } ]

这样不管访问URL::8080/#/,还是URL::8080/#/home_page,都可以访问到指定的视图了

Vue开发之基础路由

Vue开发之基础路由

2.7 JS操作路由

JS操作路由就是通过JS控制页面的跳转和返回

首先修改src/views/Home.vue文件,在页面上添加一个button按钮,button按钮的值为"返回上一页",button点击事件为"handleClick"

<template> <div> <img alt="Vue logo" src=""> <HelloWorld msg="Welcome to Your Vue.js App"/> <button @click="handleClick">返回上一页</button> // 新添加的button按钮 </div> </template> <script> // @ is an alias to /src import HelloWorld from '@/components/HelloWorld.vue' export default { name: 'home', components: { HelloWorld }, methods:{ handleClick () { this.$router.back() } } } </script>

浏览器打开URL::8080/#/,点击About标签跳转到about页面

Vue开发之基础路由

然后再点击Home标签,跳转到home页面

点击"返回上一页"按钮,页面返回到当前页的上一页,即about页面了

Vue开发之基础路由

返回上一页的JS语句也可以写成:

handleClick () { this.$router.go(-1) }

或者跳转到指定页面:

handleClick () { this.$router.push({ name:'about', }) }

跳转到指定页面的同时需要在URL上添加参数时,可以加query选项

handleClick () { this.$router.push({ name:'about', query:{ name:'orange', price:'5' } }) }

在home页点击"返回上一页"时,URL会跳转到about页面,并在URL上添加query中定义的参数

Vue开发之基础路由

跳转到前面定义的/argu这个路由

先在src/router/router.js文件中,为/argu这个路由添加名字

{ path:'/argu/:name', name:'argu', component:() => import('@/views/argu.vue') }

然后修改src/views/Home.vue文件中的handleClick方法

handleClick () { this.$router.push({ name:'argu', params:{ name:'orange', } }) }

在home页点击"返回上一页"时,URL会跳转到about页面

Vue开发之基础路由

上面的方法也可以用ES6的语法重写,也可以达到同样的效果

handleClick () { const name = 'banana' this.$router.push({ path:`/argu/${name}` // 这里的 ` 是键盘上Ese下面的那个键 }) }

或者

handleClick () { this.$router.push({ name:`argu`, params:{ name:'banana' } }) }

在home页点击"返回上一页"时,浏览器页面显示为

Vue开发之基础路由

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpzgsf.html