上篇文章我們用vue-cli腳手架工具做了個簡單的hello world頁面,但是我們破壞了原來的流程,而正常的訪問頁面應該是通過路由來實現的。
那么什么是路由呢?
路由就是通過不同的url來訪問不同的內容。

下面我們就通過路由來訪問不同的頁面吧~~~
我們用vue-cli新建個項目test1。並運行;

如上圖可以訪問到默認的歡迎頁面。
那么這個頁面在vue中是怎么組成的呢?可以分析一下:
先看App.vue這個入口組件。
、
再來看Hello.vue這個組件。

好了,這個歡迎頁面我們基本分析清楚了,那么路由又是如何工作的呢?
1.我們在components下面新建個Helloworld組件。Helloworld.vue代碼如下:
<!--模板部分-->
<template>
<div class="container">
<h1>hello,world!</h1>
<p>{{test}}</p>
</div>
</template>
<!--js部分-->
<script>
export default {
name: 'helloworld',
data() {
return {
test: 'this is a test'
};
}
}
</script>
<!--樣式部分-->
<style>
.container {
background: #aaa;
color: blue;
}
</style>
2.把Helloworld.vue組件加入到router下面的index.js中的路由。index.js代碼如下:
import Vue from 'vue' import Router from 'vue-router' import Hello from '@/components/Hello' import HelloWorld from '@/components/Helloworld'//我們新定義的組件 Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'Hello', component: Hello }, {//新路由 path: '/helloworld', name: 'HelloWorld', component: HelloWorld } ] })
3.main.js代碼如下:
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router'//index.js會自動尋找到,也可以寫全(import router from './router/index') Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, template: '<App/>', components: { App } })
4.我們在瀏覽器地址欄輸入http://localhost:8080,正常應該是顯示首頁;然后我們改一下url,輸入http://localhost:8080/#/helloworld,這個就是我們自定義的組件。

這個時候我們就用路由實現了兩個頁面之間的跳轉了。
注意:在服務開始之前,打開build文件夾下的webpack.base.conf.js這個文件:我們找到module一欄,將eslint-loader這個模塊屏蔽掉。因為這個是格式檢查的工具,如果不關掉,它連多個空格都會提示你改,否則不讓過,所以只好干掉它。如圖:

