vue-router的配置使用
三个基本概念
const routes = [ { path: '/home', component: Home }, { path: '/about', component: About } ]
const router = new VueRouter({ routes // routes: routes 的简写 })
const app = new Vue({ router }).$mount('#app')
把某种模式匹配到的所有路由,全部映射到同一个组件。例如,有一个User组件,对于所有ID各不相同的用户,都要用这个组件来渲染。那么,我们可以在vue-router的路由路径中使用【动态路径参数】
当使用路由参数时,例如从/user/foo导航到/user/bar,原来的组件实例会被复用。因为两个路由都渲染同一个组件,比起销毁再创建,复用则显得更加高效。这也意味着组件的生命周期钩子不会再被调用
const User = {
template: '<div>User</div>
}
const router = new VueRouter({
routes: [
// 动态路径参数,以冒号开头
{ path: '/user/:id', component: User }
]
})
由我们的页面结构所决定. 当我们进入到home页面的时候,它下面还有分类,如手机系列,平板系列,电脑系列。当我们点击各个分类的时候,它还是需要路由到各个部分,如点击手机,它肯定到对应到手机的部分 vue 提供了childrens 属性,相当于我们所写的routes
const routes = [
{
path:"/home",
// 下面这个属性也不少,因为,我们是先进入home页面,才能进入子路由
component: home,
// 子路由
children: [
{
path: "phone",
component: phone
},
{
path: "tablet",
component: tablet
},
{
path: "computer",
component: computer
}
]
}
];
给路由加一个name 属性
{
path: "/user/:id",
name: "user",
component: user
}
使用:在router-link 中to 属性就可以使用对象
<router-link to="/user/123">User123</router-link> // 和下面等价
<router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link>
// 当使用对象作为路由的时候,to前面要加一个冒号,表示on-bind绑定,否则会被当成对象
借助router的实例方法,通过编写代码实现 点击< router-link >时,这个方法会在内部调用,所以说,点击< router-link :to=”…”>等同于调用router.push(…) this.$router.history.push('要跳转路由的地址')
<script>
export default {
methods:{
toCart(){
//this.$router.push("/carts");
//this.$router.push({path:"/carts"});
this.$router.push({path:"/carts?a=123"});
}
}
}
</script>