上一章說道:十分鐘上手-搭建vue開發環境(新手教程)http://www.lxweimin.com/p/0c6678671635
開發環境搭建好之后,那么開始新添加一些頁面,構建最基本的vue項目,本章會手把手教你用vue-cli構建一個簡單的路由應用。
1:啟動項目,啟動之后,第一個vue項目環境搭建成功
npm run dev
2:創建后目錄結構如下:
build 項目構建(webpack)相關代碼
config 配置目錄,包括端口號等。我們初學可以使用默認的。
node_modules npm 加載的項目依賴模塊
assets: 放置一些圖片,如logo等。
components: 目錄里面放了一個組件文件,可以不用。
App.vue: 項目入口文件,我們也可以直接將組件寫這里,而不使用 components 目錄。
main.js: 項目的核心文件。
static 靜態資源目錄,如圖片、字體等。
test 初始測試目錄,可刪除
.xxxx文件 這些是一些配置文件,包括語法配置,git配置等。
index.html 首頁入口文件,你可以添加一些 meta 信息或統計代碼啥的。
package.json 項目配置文件。
README.md 項目的說明文檔,markdown 格式
3:開始增加自己的文件,目錄結構如下,dist是打包后生成的,不需要新建,components存放組件,common存放了公用的組件頭部和底部,router存放路由配置文件。
用 Vue.js + vue-router 創建單頁應用,是非常簡單的。使用 Vue.js ,我們已經可以通過組合組件來組成應用程序,當你要把 vue-router 添加進來,我們需要做的是,將組件(components)映射到路由(routes),然后告訴 vue-router 在哪里渲染它們。下面是一個基本例子:
4:開始創建四個組件 ,分別命名為abcd.vue頁面
5:然后在router index.js文件里面定義路由
index.js 代碼
import Vue from 'vue'
import Router from 'vue-router'
/*import HelloWorld from '@/components/HelloWorld'*/
import a from '@/components/a'
import b from '@/components/b'
import c from '@/components/c'
import d from '@/components/d'
Vue.use(Router)
export default new Router({
routes: [
/* {
path: '/',
name: 'HelloWorld',
component: HelloWorld
},*/
{
path: '/a',
name: 'a',
component: a
},
{
path: '/b',
name: 'b',
component: b
},
{
path: '/c',
name: 'c',
component: c
},
{
path: '/d',
name: 'd',
component: d
}
]
})
6:在app.vue中使用router-link做跳轉
app.vue代碼
<template>
<div id="app">
<div class="list-group">
<div class="navbottom">
<router-link to="a">跳轉1</router-link>
</div>
<div class="navbottom">
<router-link to="b">跳轉2</router-link>
</div>
<div class="navbottom">
<router-link to="c">跳轉3</router-link>
</div>
<div class="navbottom">
<router-link to="d">跳轉4</router-link>
</div>
</div>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'app'
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
.list-group {
position: absolute;
bottom: 0;
}
.navbottom {
width: 5rem;
float: left;
}
</style>
7:注意,這段代碼用來盛放a,b,c,d,頁面的信息<router-view></router-view>
8:最終效果如下,點擊路由,跳轉到不同的頁面。OK,手把手教你用vue-cli構建一個簡單的路由應用,沒錯,就是這么的簡單。
原文作者:祈澈姑娘
技術博客:http://www.lxweimin.com/u/05f416aefbe190后前端妹子,愛編程,愛運營,愛折騰。
堅持總結工作中遇到的技術問題,堅持記錄工作中所所思所見,私信回復1,拉你進前端技術交流群