vue-路由使用


路由安裝

終端下載路由插件 npm install vue-router --save-dev

 

配置

在main.js中引入插件

1 //Router 為自定義名   vue-router 為插件的名字
2 
3 import Vue from 'vue'
4 
5 import Router from 'vue-router' 

 

注冊使用

//注冊使用 vue-router

Vue.use(Router)

 

配置路由

 1 const router = new Router({
 2   routes : [
 3     {path : "/" ,name : "home" component: Home},
 4     {path : "/helloworld" , name : "helloworld",component: HelloWorld}
 5   ],
 6   mode : "history" //去掉路由地址后面的#
 7 })
 8 
 9 //可以將routes單獨抽離出來 
10 
11 const routes = [
12     {
13         path : "/" ,    //設置路由路徑
14         name : "home",
15         component: Home   // home在main.js里面注冊的組件名,將要跳轉到的組件
16     },
17 
18     {path : "/helloworld" , name : "helloworld",component: HelloWorld},
19 
20     {path : "*" , redirect: '/'}  //當點擊不存在路徑時 默認 跳轉到路徑 '/'
21 ]
22 
23 const router = new Router({
24   routes,
25  linkActiveClass: 'class' //設置路由比標簽選中顏色
26 mode : "history" 27 })

 

需要在main.js中 vue實例中引入router 

1 new Vue({
2  router, 
3   el: '#app',
4   components: { App },
5   template: '<App/>'
6 })

 

二級路由的設置

 1 //二級路由在當前路由下添加 children數組 
 2 
 3 const routes = [
 4     {
 5         path : "/about" ,  //設置路由路徑
 6         name:'about',
 7         component: About,
 8         redirect: '/about1',  //設置當前頁面默認顯示的子路由
 9         children:[  //二級路由
10             {path : "/about1" ,name:'about1', component: About1},
11             {path : "/about2" ,name:'about2', component: About2},
12             {path : "/about3" ,name:'about3', component: About3},
13             {path : "/about3" ,name:'about3', component: About3},
14           ]
15     },
16 ]
17 
18 const router = new Router({
19   routes,
20   mode : "history"
21 })    

 

跳轉的幾種寫法

標簽<router-link to=""></router-link>

一、

1 <!-- to屬性里面填入路徑(在main.js中設置的路徑) -->
2 <!-- tag屬性可以設置 標簽的展示 tag="div"標簽是以div形式的展示 -->
3 4 <router-link tag="div" to="/home">首頁</router-link>

二、

<!-- 通過 注冊路由時設置的 name 屬性 -->

<router-link :to="{name : 'home'}">首頁</router-link>

通過name屬性
{path : "/home" ,name:'home', component: Home},

三、

 

<!-- 可以動態設置路徑 -->

<router-link :to="home">新聞</router-link>

<!-- 可以通過data動態設置路徑 --> data(){ name : '/home' }

 

通過name屬性實現<router-link></router-link>的復用 

 

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

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

<router-view name="home3"></router-view>
const routes = [
  {
    path : "/" ,  
    name:'home', 
    components: {   //components  這里有 s 
        default : Home,  //  當前的home頁面
        //為復用的 路由設置 屬性名
        'home1' : Home1,  
        'home2' : Home2,
        'home3' : Home3,
    
      }
    },
]

 


免責聲明!

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



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