使用 Vue.js 做項目的時候,一個頁面是由多個組件構(gòu)成的,所以在跳轉(zhuǎn)頁面的時候,并不適合用傳統(tǒng)的 href,于是 vue-router 應(yīng)運(yùn)而生。
路由,其實(shí)就是指向的意思,當(dāng)我點(diǎn)擊頁面上的home按鈕時,頁面中就要顯示home的內(nèi)容,如果點(diǎn)擊頁面上的about 按鈕,頁面中就要顯示about 的內(nèi)容。Home按鈕 => home 內(nèi)容, about按鈕 => about 內(nèi)容,也可以說是一種映射. 所以在頁面上有兩個部分,一個是點(diǎn)擊部分,一個是點(diǎn)擊之后,顯示內(nèi)容的部分。
點(diǎn)擊之后,怎么做到正確的對應(yīng),比如,我點(diǎn)擊home 按鈕,頁面中怎么就正好能顯示home的內(nèi)容。這就要在js 文件中配置路由。
官方文檔: https://router.vuejs.org/zh-cn/essentials/getting-started.html
Vue-Router的最簡單使用
1.先注冊路由
2.將路由注冊到VM組件中
3.定義組件
4.頁面定義跳轉(zhuǎn)路徑
<!DOCTYPE html><html>  <head>    <meta charset="UTF-8">    <title></title>    <script src="lib/vue.min.js"></script>    <script src="lib/vue-router-3.0.1.js"></script>    <style type="text/css">    </style>  </head>  <body>        <div id="app">      <!--        由于Vue-router的hash匹配原則所以我們需要在原定義的路徑上加一個#號      -->      <a href="#/login" rel="external nofollow" rel="external nofollow" >登錄</a>      <a href="#/register" rel="external nofollow" rel="external nofollow" >注冊</a>      <router-view></router-view>    </div>  </body>  <script>    var login={      template:'<h1>登錄組件</h1>'    }    var register={      template:'<h1>注冊組件</h1>'    }    var routerObj = new VueRouter({      routes:[      //此處的component只能使用組件對象,而不能使用注冊的模板的名稱        {path:"/login",component:login},        {path:"/register",component:register}      ]    })    var vm = new Vue({      el:'#app',      data:{      },      methods:{              },      router:routerObj//將路由規(guī)則對象注冊到VM實(shí)例上    })  </script></html>使用Router-Link替代a標(biāo)簽
這么做主要是為了去掉a標(biāo)簽中的為了匹配hash地址的“#”,如下
<!DOCTYPE html><html>  <head>    <meta charset="UTF-8">    <title></title>    <script src="lib/vue.min.js"></script>    <script src="lib/vue-router-3.0.1.js"></script>    <style type="text/css">    </style>  </head>  <body>        <div id="app">      <!--        由于Vue-router的hash匹配原則所以我們需要在原定義的路徑上加一個#號      --><!--      <a href="#/login" rel="external nofollow" rel="external nofollow" >登錄</a>      <a href="#/register" rel="external nofollow" rel="external nofollow" >注冊</a>-->      <router-link to="/login" tag="span">登錄</router-link>      <router-link to="/register">注冊</router-link>      <router-view></router-view>    </div>  </body>  <script>    var login={      template:'<h1>登錄組件</h1>'    }    var register={      template:'<h1>注冊組件</h1>'    }    var routerObj = new VueRouter({      routes:[      //此處的component只能使用組件對象,而不能使用注冊的模板的名稱        {path:"/login",component:login},        {path:"/register",component:register}      ]    })    var vm = new Vue({      el:'#app',      data:{      },      methods:{              },      router:routerObj//將路由規(guī)則對象注冊到VM實(shí)例上    })  </script></html>            
新聞熱點(diǎn)
疑難解答
圖片精選