天天看點

Vue簡單建立一個項目(八)

Vue的路由實際上就是在APP根元件的挂載元件中做不同的切換,就是動态的去挂載。

vue-router(這個和vue-resource一樣都是Vue自己的仔)

cnpm install vue-router --save

在main.js引入:

import VueRouter from ‘vue-router’;

Vue.use(VueRouter);

之前我們做的父子元件都是把子元件作為父元件的一個子產品去調用的,然而我們現在是路由切換,那就不是一個概念了,而是相當于頁面跳轉了。

在main.js裡面我們可以引用要跳轉的元件:

A->Home

B->News

import Home from ‘./components/Home.vue’;

import News from ‘./components/News.vue’;

定義路由:

const routes = [
  { path: '/home', component: Home },
  { path: '/news', component: News },
]
           

執行個體化VueRouter 注意:名字

const router = new VueRouter({ routes // (縮寫)相當于 routes: routes })
上面我要提一嘴:const xxx=[]裡的xxx ,必須與
new VueRouter({   routes :xxx })裡的xxx對應上!!!
           

挂載路由

new Vue({
  el: '#app',
  router,//在這個地方挂載
  render: h => h(App)
})
           

路由展示的地方要根據位置而定,目前是放在APP根元件裡的

<router-view></router-view> 放在 App.vue
           

這個時候其實你要輸入的網址就是:

127.0.0.1:8080/#/home

或者是:

127.0.0.1:8080/#/news

可以做類似a标簽跳轉的連結:

<router-link to="/home">首頁</router-link>
<router-link to="/news">新聞</router-link>
           

重定向别名的意思就是,我想讓項目在加載組建的時候就設定為我喜歡的,或者讓别人眼前一亮的頁面!!!很通俗易懂吧!!!

const routes = [
  { path: '/home', component: Home },
  { path: '/news', component: News },

  { path: '*', redirect: '/home' }   /*預設跳轉路由,這個就是重定向*/
]