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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM