VUE

路由router的注意事项

2019-03-28  本文已影响169人  樊小勇

一、router简单函数

1.this.$router.push()

描述:跳转到不同的url,但这个方法回向history栈添加一个记录,点击后退会返回到上一个页面。

用法:

image

2.this.$router.replace()

描述:同样是跳转到指定的url,但是这个方法不会向history里面添加新的记录,点击返回,会跳转到上上一个页面。上一个记录是不存在的。

3.this.$router.go(n)

相对于当前页面向前或向后跳转多少个页面,类似 window.history.go(n)。n可为正数可为负数。正数返回上一个页面

image

二、小总结

this.$router.push("组建名")  //跳转  这个可以用在平行组件 我在子路由中使用发现不好用  具体不太清楚
this.$router.push({name:" 组件名 "});
this.$router.push({path:" 路径 "})
this.$router.push({name:"组件名",params:{code:2 }})   //跳转加传值
this.$route.params.code //接收参数值
<router-link  to=“/user/23”>K<router-link> //这中需要    user /:id
<router-link  :to={name:"ming" ,params:{name:"wangye"}}>ad<router-link>        //这两种路由都不需要user /:id
<router-link :to="{path:'/user/admin ' , params:{name:' wnahg ', age: ' sdsad  '}}">sd</router-link>
this.$router.push({path:'/user', query:{age:23} });
this.$route.query.age

三、路由中有三个基本的概念 route, routes, router

四、动态路由-嵌套路由

<router-link  to="/user/25">

{  path : "/user/:id",  component : user  }
<router-link  to="/home/user">

{

path::"/home",

component: home,

children:[

     {  path:"/user",  component:user } 

  ]

} 
{
path: "/user/:id",
component:"user",
component:user
}
<router-link   to = "user/25">  user </router-link>
<router-link  :to = { name:"user", params :{ userID : 25 }}>  user </router-link>
// 当使用对象作为路由的时候,to前面要加一个冒号,表示绑定
主要应用在按钮上  调用   router.push()方法
通过  this.$router.push("user")    //就可以跳转到对应的组件
   // 还可以  传值
this.$router.push({ name:user , params:{ code:2 }})
this.$route.params.code  接收值
meta: {
               requireAuth: true,             //这个还不知道什么意思    和设置title 无关
               wrapper: true                   // 同上
               title:首页
     }
{

       path:'/',                   //因为  程序启动时 第一个进入的就是 /    所以用重定向避免错误

       name: 'default',

       redirect: '/index'
 },

四、深入router

const User = {

    template: '...',

    watch: {

        '$route' (to, from) { // 对路由变化作出响应... }

    }

}
const User = {
      template: '...',
      beforeRouteUpdate (to, from, next) {
            // react to route changes...

            // don't forget to call next()
    }

}
<router-view></router-view> 

 <router-view name="a"></router-view>

一个视图使用一个组件渲染,因此对于同个路由,多个视图就需要多个组件。确保正确使用 components 配置(带上 s):

routes: [ {

    path: '/',

    components: {

        default: Foo,

        a: Bar

    }

} ]
const router = new VueRouter({

    mode: 'history',

    routes: [...]

})

当你使用 history 模式时,URL 就像正常的 url,例如 http://yoursite.com/user/id不过这种模式要玩好,还需要后台配置支持。因为我们的应用是个单页客户端应用,如果后台没有正确的配置,当用户在浏览器直接访问 http://oursite.com/user/id 就会返回 404,这就不好看了。所以呢,你要在服务端增加一个覆盖所有情况的候选资源:如果 URL 匹配不到任何静态资源,则应该返回同一个 index.html 页面,这个页面就是你 app 依赖的页面。

this.$router.push({name: '.....', params: {id: .....}})
params传参, 路径不能使用path 只能使用name,否则params将无效
取数据:  this.$route.params.id

query 传参

params传参, 路径可以使用path或者name
this.$router.push({path: '.....', query: {id: .....}})
取数据:  this.$route.query.id

上一篇下一篇

猜你喜欢

热点阅读