詳解windows下vue-cli及webpack 構建網站(四) 路由vue-router的使用,vue-clivue-router
windows下vue-cli及webpack 構建網站(一)環境安裝
windows下vue-cli及webpack 構建網站(二)匯入bootstrap樣式
windows下vue-cli及webpack 構建網站(三)使用組件
1、本篇文章是建立在以上三篇文章的基礎上的。
2、安裝 vue-router 外掛程式,運行cmd進入到項目目錄下面,運行以下命令:
cnpm install vue-router --save-dev
3、在src檔案夾下面建立一個檔案夾page用於存放模板檔案,然後分別在這個檔案夾下面建立 index.vue、list.vue兩個檔案,然後開啟index.vue粘貼以下代碼:
<template> <div class="jumbotron"> <h1>這裡是首頁!</h1> </div> </template>
儲存之後再開啟list.vue粘貼以下代碼:
<template> <div class="list-group"> <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="list-group-item active"> 這裡是列表頁 </a> <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="list-group-item">Dapibus ac facilisis in</a> <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="list-group-item">Morbi leo risus</a> <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="list-group-item">Porta ac consectetur ac</a> <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" class="list-group-item">Vestibulum at eros</a> </div> </template>
好了,兩個頁面的內容都準備好了,接下來我們修改入口檔案app.vue的內容吧
4、開啟src檔案夾下面的app.vue檔案,修改代碼為
<template> <div> <HtmlHeader></HtmlHeader> <router-view class="view" keep-alive transition transition-mode="out-in"> </router-view> <HtmlFooter></HtmlFooter><span style="white-space:pre"> </span> </div> <span style="white-space:pre"> </span> </template> <script> import HtmlHeader from './components/header' import HtmlFooter from './components/footer' export default { components: { HtmlHeader, HtmlFooter } } </script>
這裡用了 router-view 來把剛才建立的兩個頁面載入到這裡來
修改了入口檔案接下來就是要進行路由規則的配置了。
5、在src檔案夾下面建立一個檔案夾config用來存放路由配置,在config檔案夾下面建立routes.js檔案並開啟,然後粘貼以下代碼並儲存:
//載入模板檔案 import index from '../page/index' import list from '../page/list' //路由規則設定 export default [ { path: '/', component: index }, { path: '/list', component: list } ]
現在路由設定檔也已經配置好了,我們接下來就是要開啟sec檔案夾下面的main.js檔案設定路由使用了
6、開啟main.js 檔案,在頭部加入以下代碼
// 引用路由外掛程式 import VueRouter from 'vue-router' // 試用路由外掛程式 Vue.use(VueRouter) //引入路由設定檔 import routes from './config/routes' // 使用設定檔規則 const router = new VueRouter({ mode: 'history', base: __dirname, routes: routes })
這個是引入路由外掛程式並且使用,然後載入路由規則
接著把
new Vue({ el: '#app', template: '<App/>', components: { App } })
修改為
const app = new Vue({ router: router, render: h => h(App) }).$mount('#app')
設定完之後整個頁面代碼
7、載入開始運行 npm run dev 查看效果吧,開啟http://localhost:8080 和http://localhost:8080/list 就可以看到不同的效果了
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。