美文网首页
Vue学习笔记[14]-vue-router使用嵌套路由&传递路

Vue学习笔记[14]-vue-router使用嵌套路由&传递路

作者: 神楽花菜 | 来源:发表于2019-11-23 15:49 被阅读0次

    当前我们配置的路由都只有一层,要配置多层路由,需要用到嵌套路由。

     //index.js
    const routes = [
    //...
      {
        path:'/home',
        component: Home,
        children:[
          {
            path: 'news',
            component:HomeNews
          },
          {
            path: 'message',
            component: HomeMessage
          }
        ]
      },
    ]
    
    const router = new VueRouter({
      mode: 'history',
      base: process.env.BASE_URL,
      routes
    })
    
    export default router
    
    

    参数传递

    在跳转页面时,我们有时候会希望在不同页面之间传递一些数据。
    传递参数有两种方式:params和query

    1. params

    传参数:

    //app.js
    <router-link :to="'/user/'+userID" tag='button'> USER </router-link>
    <router-view></router-view>
    //...
    <script>
    data() {
        return {
          userID: 5050
        }
      },
    </script>
    
    //index.js
      {
      path: '/home/user/:userID'
      component: User
      }
    

    取参数:

    //user.vue
    <template>
      <div>
          <h2>user:{{userID}}</h2>
      </div>
    </template>
    
    <script>
    export default {
        name:'User',
    computed: {
        userID() {
            return this.$route.params.userID 
        }
    },
    };
    </script>
    

    2. query

    传参数:

    • index.js
    const routes = [ 
    //... 
    {
        path:'/user',
        component:User
      }
    ]
    

    app.vue

    <template>
      <router-link :to="{path:'/user',query:userQuery}" tag='button'> USER </router-link>
      <router-view></router-view>
    </template>
    <script>
    data(){
      return{
     //...
      userid:5050,
      name:'kagura'
      }
    }
    </script>
    
    • user.vue
    
    <template>
      <div>
          <h2>user:{{userID}}</h2>
          <h2>name:{{name}}</h2>
      </div>
    </template>
    
    <script>
    export default {
        name:'User',
    computed: {
        userID() {
            return this.$route.query.userid 
        },
        name(){
            return this.$route.query.name
        }
    },
    };
    </script>
    

    相关文章

      网友评论

          本文标题:Vue学习笔记[14]-vue-router使用嵌套路由&传递路

          本文链接:https://www.haomeiwen.com/subject/hzdhwctx.html