vue 路由router
阿新 • • 發佈:2018-11-14
路由可以讓根元件自動掛載不同的元件。即可以動態的掛在而不用手動掛載。
1. 安裝 npm install vue-router --save 2. 在main.js 裡引入並使用 import VueRouter from 'vue-router' Vue.use(VueRouter) 3. 配置路由 (1)建立元件,引入元件 (2)定義路由 const routes[ {path:'/foo', component: Foo}, {path:'/bar', component: Bar} ] (3)例項化VueRputer const router = new Vuerouter({ routes //(縮寫)相當於routes:routes }) (4)掛載 new Vue({ el:'#app', router, render: h=>(App) }) (5)在App.vue裡面<router-view></router-view> (6)在App.vue裡面 <router-link to="/foo">go to Foo</router-link> <router-link to="/bar">go to Bar</router-link>
next is the App.vue
1 <template> 2 3 4 <div id="app"> 5 6 7 <router-link to="/home">首頁</router-link> 8 <router-link to="/news">新聞</router-link> 9 10 <hr> 11 12 <router-view></router-view> 13 14 </div> 15</template> 16 17 <script> 18 19 export default { 20 data () { 21 return { 22 23 msg:'你好vue' 24 } 25 } 26 27 } 28 </script> 29 <style lang="scss"> 30 31 32 </style>
next is the main.js
1 import Vue from 'vue';2 import App from './App.vue'; 3 4 5 6 import VueRouter from 'vue-router'; 7 8 Vue.use(VueRouter); 9 10 11 //1.建立元件 12 13 14 import Home from './components/Home.vue'; 15 16 import News from './components/News.vue'; 17 18 19 //2.配置路由 注意:名字 20 21 const routes = [ 22 { path: '/home', component: Home }, 23 { path: '/news', component: News }, 24 25 { path: '*', redirect: '/home' } /*預設跳轉路由*/ 26 ] 27 28 29 //3.例項化VueRouter 注意:名字 30 31 const router = new VueRouter({ 32 routes // (縮寫)相當於 routes: routes 33 }) 34 35 36 37 38 //4、掛載路由 39 40 new Vue({ 41 el: '#app', 42 router, 43 render: h => h(App) 44 }) 45 46 47 //5 <router-view></router-view> 放在 App.vue