vue之router-view组件的使用

开发的时候有时候会遇到一种情况,比如 :点击这个链接跳转到其他组件的情况,通常会跳转到新的页面,蛋是,我们不想跳转到新页面,只在当前页面切换着显示,那么就要涉及到路由的嵌套了,也可以说是子路由的使用。

以饿了么订餐的情景来说吧,在同个页面,切换显示不同组件的相应内容,同时地址栏的地址是会变的

怎么实现它呢?

  首先 我们在导航组件navbar.vue中写了三个导航链接,他们对应地址分别为:/food,/rating,/seller,点击每个导航链接会跳转到不同的组件,并且加上<router-view></router-view>这个标签

navbar.vue:

<template>
    <div class="navbar">
        <ul id="main">
            <li><router-link  to="/food" >商品</router-link></li>
            <li><router-link  to="/rating">评价</router-link></li>
            <li><router-link  to="/seller">商家</router-link></li>
 
        </ul>
        
            <!-- 路由匹配到的组件将显示在这里 -->
           <router-view></router-view>
    </div>
</template>

然后,我们在index.vue引入navbar.vue:

index.vue

 
<template>
    <div class="index">
        <div class="nav"></div>
        <div class="shop-header">
            <div class="imgbox"><img src="../../static/img/56.jpg" alt="" /></div>
            <h2>黄蜀郞鸡公煲<span class="ico"></span></h2>
            <p class="info1"><span>*4.6</span><span>月售738</span><span>商家配送约44分钟</span><span>距离345m</span></p>
            <p class="info2">店内免费涮煲,(蔬菜、小料、主食、糕点、凉菜、水果、免费吃)闻香识辣,入口知麻,一锅两吃,独具特色!!!外卖米饭请自点!!评价问题商家会一一看,可能不能及时回复。有问题详询18232966036</p>
 
        </div>
 
 
         <!--在这里引入navbar组件在这里引入navbar组件在这里引入navbar组件在这里引入navbar组件-->
        <navbar></navbar>
         <!--在这里引入navbar组件在这里引入navbar组件在这里引入navbar组件在这里引入navbar组件-->
        
        
        
    </div>
</template>
 
<script>
    import navbar from '@/components/navbar'
    
    import food from '@/components/food'
    export default {
        name: 'HelloWorld',
        data() {
            return {
                
                msg:[]
            }
        },
 
        components: {
            navbar
            
        }
    }
</script>
 
<!-- Add "scoped" attribute to limit CSS to this component only -->
 
<style lang="stylus">
    @import '../../static/css/index.styl';
</style>

最后,路由都是怎么配的呢,在index.js中:

{
      path: '/',
      name: 'index',
      component: index,
      redirect:'/food',
      children:[
      {
        path: 'food',
        name: 'food',
        component: food
      },
      {
        path: 'seller',
        name: 'seller',
        component: seller
      },
      {
        path: 'rating',
        name: 'rating',
        component: rating
      }
      ]
    },

原文链接:https://blog.csdn.net/luoyu6/article/details/80098145

原文地址:https://www.cnblogs.com/fei-H/p/11362591.html