Vue-router 使用方法:目的是路由在不同页面中的跳转
- 在搭建项目的时候,vue init webpack my-project 会默认提示我们是否安装,路由跳转的。当我们默认选择y 的时候,在App.vue 根组件中,默认的是存在<router-view> 这个是vue实例存在的 表示路由的视图
- <router-link> 相当于HTML的a链接,跳转。
第一个要求,实现A页面和B页面的跳转
当输入http://localhost:8080/a 跳转到A路由页面
当输入http://localhost:8080/b 跳转到B路由页面
在components 组件中创建组件A.vue B.vue 组件。
然后在src/router/index.js 中注册和导入组件
import A from '@/components/A'
import B from '@/components/B'
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/hello-world',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/a',
name: 'A',
component:A
},
{
path: '/b',
name: 'B',
component:B
}]
})
就OK了。
router-view和router-link是vue-router官方提供的两个组件,router-view会替换为路由对应的组件,router-link相当于a标签,点击后会加载to属性中路由对应的组件
第二案例: 需求 我们可能需要 点击http://localhost/a/aa的时候 可以访问到aa
点击a 的时候 可以访问到a
最后在某些真实案例中,还需要重定向的问题。就是我们点击爸爸a 的时候。就直接进入aa 组件页面中,这个符合真实的场景。当如果我们左边是a 是侧边栏,左边/aa 是内容 如果不重定向,那么就可能造成页面的只显示/a 不显示/aa 就不符合用户需求的。
解决方法:
在爸爸中加入儿子 router/index.js
{
path: '/a',
name: 'A',
component: A,
redirect: '/a/aa',
children: [{
path: '/a/aa',
name: 'AA',
component: AA
}]
}
然后还要引入自己创建的AA.vue组件.
当然这个组件同样是在router/index.js 中引入的
Import AA from ‘@components/AA’
第三题: 案例在需求 再升级了 就是
http://localhost/8080/a/aa/2143434
从而返回一个指定的商品
http://localhost/8080/a/aa/5u923u523
从而返回动态的参数 展示不同产品。
解决方案:
{
path: '/a',
name: 'A',
component: A,
redirect: '/a/aa',
children: [
{
path: '/a/aa',
name: 'AA',
component: AA
},
{
path: '/a/:id',
name: 'AA2',
component: AA2
}
]
},
然后在自己的注册组件中带有参数的传递。
{{$route.params.id}}
在页面中输入message = hello
http://localhost:8081/#/a/aa?message=hello
通过 {{$route.query.message}}
就可查询到 message 后面的参数 就会展示在页面上 hello.
方案在升级 编程式的方式 实现路由:
点击B页面 跳转到A页面
<button @click=”jump”>jump</button>
export default {
methods: {
jump () {
this.$router.push({
path:'/a/aa',
query: {
message:'shiyufneg0'
}
})
}
}
}
不向history插入记录this.$router.replace('/a/123')
回退 this.router.go(-1); 可以点击回到前面的组件页面。